面试题06:从尾到头打印链表(C++)

题目地址:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/

题目描述

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)

题目示例

输入:head = [1,3,2]

输出:[2,3,1]

解题思路

思路1:两个数组存放元素节点,其中第一个数组用于存放链表中所有节点,第二个数组存放倒序的元素。

思路2:使用栈依次存入节点,然后再从栈中取出节点可实现逆序,即从尾到头打印链表。

思路3:利用哑结点改变链表结构,从而反转链表。

程序源码

思路1

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> reversePrint(ListNode* head) {
        if(head == nullptr) return {};
        vector<int> arr;
        vector<int> res;
        while(head)
        {
            arr.push_back(head->val);
            head = head->next;
        }
        for(int i = arr.size() - 1; i >= 0; i--)
        {
            res.push_back(arr[i]);
        }
        return res;
    }
};

思路2

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> reversePrint(ListNode* head) {
        vector<int> revResult;
        stack<int> sk;
        while(head != nullptr)
        {
            sk.push(head->val);
            head = head->next;
        }
        while(!sk.empty())
        {
            revResult.push_back(sk.top());
            sk.pop();
        }
        return revResult;
    }
};

思路3

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> reversePrint(ListNode* head) {
        if(head == nullptr) return {};
        ListNode* dummyHead = nullptr;
        ListNode* cur = head;
        while(cur)
        {
            ListNode* node = cur->next;
            cur->next = dummyHead;
            dummyHead = cur;
            cur = node;
        }
        vector<int> res;
        while(dummyHead)
        {
            res.push_back(dummyHead->val);
            dummyHead = dummyHead->next;
        }
        return res;
    }
};
----------------------------------- 心之所向,素履所往;生如逆旅,一苇以航。 ------------------------------------------
原文地址:https://www.cnblogs.com/wzw0625/p/12501851.html