从尾到头打印链表

题目描述

输入一个链表,从尾到头打印链表每个节点的值
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> res;
        vector<int> stack;
        while(head)
        {
            stack.push_back(head->val);
            head=head->next;
        }
        for(int idx=stack.size()-1; idx>=0; --idx)
        {
            res.push_back(stack[idx]);
        }
        return res;
    }
};

 一个空间复杂度为O(1)的方法,不用辅助栈,考虑链表的置逆

 1 class Solution {
 2 public:
 3 ListNode * reverseList(ListNode *head)
 4 {
 5     ListNode *p1=head->next;
 6     ListNode *p2=NULL;
 7     head->next=NULL;
 8     while(p1)
 9     {
10         p2=p1->next;
11         p1->next=head;
12         head=p1;
13         p1=p2;
14     }
15     return head;
16 }
17 vector<int> printListFromTailToHead(ListNode* head)
18 {
19     vector<int> result;
20     if(head==NULL)return result;
21     ListNode *newHead=reverseList(head);
22     ListNode *tmp=newHead;
23     while(tmp)
24     {
25         result.push_back(tmp->val);
26         tmp=tmp->next;
27     }
28     reverseList(newHead);
29     return result;
30 }
31 };

 

posted @ 2017-12-19 13:30  jeysin  阅读(82)  评论(0编辑  收藏  举报