單鏈表面試題幾乎是面試的必考之題;
對於單鏈表從頭到尾打印與單鏈表的逆置不是一回事。
單鏈表的從頭到尾打印是打印出鏈表的數據。(即數據是從尾向前輸出);
一、單鏈表從頭到尾打印:
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : * val(x), next(NULL) { * } * }; */ class Solution { public: vector<int> printListFromTailToHead(struct ListNode* head) { vector<int> result; stack< ListNode*> node; struct ListNode* newhead=head; while(newhead!=NULL) { node.push(newhead); newhead=newhead->next; } while(!node.empty()) { newhead=node.top(); result.push_back(newhead->val); node.pop(); } return result; } };
二、單鏈表的逆置
/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } };*/ class Solution { public: ListNode* ReverseList(ListNode* pHead) { if(pHead==NULL) return NULL; ListNode* cur=pHead; ListNode* newHead=NULL; while(cur) { ListNode* tmp=cur; cur=cur->next; tmp->next=newHead; newHead=tmp; } return newHead; } };