首页 > 编程语言 > 详细

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

时间:2020-03-16 09:40:59      阅读:60      评论:0      收藏:0      [点我收藏+]

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

题目描述

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

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

输出:[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) {
        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;
    }
};
View Code

 

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

原文:https://www.cnblogs.com/wzw0625/p/12501851.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!