欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

面试题6:从尾巴开始打印链表

发布时间:2025/3/15 47 豆豆
生活随笔 收集整理的这篇文章主要介绍了 面试题6:从尾巴开始打印链表 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

LeetCode

相关知识点-链表

注意点1:第一个结点

链表的尾插函数一定要注意第一个结点的问题,由于第一次尾插时,头结点并没有指向任何结点,所以对于第一个结点的尾插实则是“赋值”操作,而其余结点的尾插才是指针->next的操作

void ListPushTail(ListNode** phead,int x) {ListNode* NewNode=new ListNode();NewNode->_Val=x;NewNode->_next=NUll; } if(*phead==NUll) {*phead=NewNode; } else {ListNode* current=*phead;while(current->_next!=NULL){currrent=current->_next;}current->_next=NewNode; }

所以一定要传入的是二级指针

题目

描述

输入一个链表的头结点,从尾到头打印这个链表

解决

解决方法有很多种,这里使用先顺序输入,然后交换数组前后元素即可

void swap(int* a,int* b) {int temp=*a;*a=*b;*b=temp; } int* reversePrint(struct ListNode* head, int* returnSize) {int* ret=(int*)malloc(sizeof(int)*10000);struct ListNode* current=head;int i=0;while(current!=NULL){ret[i]=current->val;i++;current=current->next;}int begin=0;int end=i-1;while(begin<end){swap(&ret[begin],&ret[end]);begin++;end--;}*returnSize=i;return ret; }

总结

以上是生活随笔为你收集整理的面试题6:从尾巴开始打印链表的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。