【剑指Offer-链表】面试题6:从尾到头打印链表

题目描述

输入一个链表,按链表从尾到头的顺序返回一个ArrayList。

思路1

从头到尾遍历链表比较简单,遍历链表时,将节点中的元素放入数组,然后将数组逆置即可。

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> v;
		if(head==nullptr)
            return v;
			
        while(head!=nullptr)
        {
            v.push_back(head->val);
            head = head->next;
        }
        vector<int> ans;
        for(int i=v.size()-1; i>=0; i--)
            ans.push_back(v[i]);
        return ans;
    }
};

这种方法不改变原来的链表。

思路2

如果能改变链表的话,可以先将链表就地逆置,然后遍历逆置后的链表即可。

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> v;
        if(head==nullptr)
            return v;
        
        //链表逆置
        ListNode* pre = nullptr;
        ListNode* cur = nullptr;
        while(head!=nullptr)
        {
            cur = head->next;
            head->next = pre;
            pre = head;
            head = cur;
        }
        head = pre;    //注意要head要重新赋值
        
        while(head!=nullptr)
        {
            v.push_back(head->val);
            head = head->next;
        }
        
        return v;
    }
};
原文地址:https://www.cnblogs.com/flix/p/12164156.html