面试题6:从尾巴开始打印链表
生活随笔
收集整理的這篇文章主要介紹了
面试题6:从尾巴开始打印链表
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
LeetCode
相關(guān)知識(shí)點(diǎn)-鏈表
注意點(diǎn)1:第一個(gè)結(jié)點(diǎn)
鏈表的尾插函數(shù)一定要注意第一個(gè)結(jié)點(diǎn)的問(wèn)題,由于第一次尾插時(shí),頭結(jié)點(diǎn)并沒(méi)有指向任何結(jié)點(diǎn),所以對(duì)于第一個(gè)結(jié)點(diǎn)的尾插實(shí)則是“賦值”操作,而其余結(jié)點(diǎn)的尾插才是指針->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; }所以一定要傳入的是二級(jí)指針
題目
描述
輸入一個(gè)鏈表的頭結(jié)點(diǎn),從尾到頭打印這個(gè)鏈表
解決
解決方法有很多種,這里使用先順序輸入,然后交換數(shù)組前后元素即可
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; }總結(jié)
以上是生活随笔為你收集整理的面试题6:从尾巴开始打印链表的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 【README2】动态规划之斐波那契数列
- 下一篇: 选择题错题总结