【链表】从尾到头打印链表(逆置链表)【剑指offer】
从尾到头打印链表
http://www.nowcoder.com/questionTerminal/d0267f7f55b3412ba93bd35cfa8e8035
思路: 1.反转链表(依次遍历链表,将插入到新链表的头部); 2.遍历新链表,将结果保存到vector中返回。
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : * val(x), next(NULL) { * } * }; */ class Solution { public: vector<int> printListFromTailToHead(ListNode* head) { ListNode* new_head = NULL; vector<int> res; //反转链表:链表的头插法,每次都把头节点插入到新链表中作为头,并更新新链表的头节点 while(head != NULL) { //备份head->next ListNode* next = head->next; //更新head->next head->next = new_head; //更新new_head new_head = head; //更新head head = next; } while(new_head != NULL) { res.push_back(new_head->val); new_head = new_head -> next; } return res; } };