链表——从尾到头遍历(链表反转)
从尾到头打印链表
http://www.nowcoder.com/questionTerminal/d0267f7f55b3412ba93bd35cfa8e8035
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : * val(x), next(NULL) { * } * }; */ class Solution { public: vector<int> printListFromTailToHead(ListNode* head) { //vector<int> ret; /*if(!head) { return ret; } ret = printListFromTailToHead(head->next); return ret;*/ /*while(head) { ret.push_back(head->val); head=head->next; } std::reverse(ret.begin(),ret.end()); return ret;*/ ListNode* pre =nullptr; ListNode* cur = head; ListNode* temp = cur; while(cur) { temp = cur->next; cur->next=pre; pre = cur; cur = temp; } vector<int > ret; while(pre) { ret.push_back(pre->val); pre = pre->next; } return ret; } };
考虑用到三个指针,分别为,现在,前一个,后一个,再用一个temp暂存!