剑指offer 3:从尾到头打印链表

本文介绍了一种使用栈的特性逆序打印链表的方法。通过遍历链表并将每个节点的值压入栈中,再依次弹出栈中的元素,实现从尾到头打印链表的功能。代码示例展示了如何创建链表、调用逆序打印函数及输出结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

利用栈的先进后出特性

#include <iostream>
#include <stack>
#include <vector>
using namespace std;

struct ListNode
{
public:
    int val;
    struct ListNode *next;
};

class Solution
{
public:


    //3 从尾到头打印链表
    //1 利用栈的先进后出特性
    vector<int>printListFromTailToHead(struct ListNode* head) {
        ListNode *node = head;
        stack<int> st;
        int count = 0;
        while (node != NULL) {
            cout << node->val << " in stack" << endl;
            st.push(node->val);
            count++;
            node = node->next;  //把链表的数装入栈中
        }

        vector<int> res(count);//
        cout << "count = " << count << endl;
        for(int i = 0; i < count && st.empty() != true; i++) {
            cout << st.top() << " in vector" << endl;
            res[i] = st.top();
            st.pop();// 把栈中的数弹出给数组

        }

        return res;
    }





};



int main()
{
    ListNode list[4];
    list[0].val = 1;
    list[0].next = &list[1];

    list[1].val = 2;
    list[1].next = &list[2];

    list[2].val = 3;
    list[2].next = &list[3];
    list[3].val = 4;
    list[3].next = NULL;

    Solution solu;
    vector<int> res = solu.printListFromTailToHead(list);
    cout << "there are" << res.size() << " datas in vector" << endl;
    for (int i = 0; i < res.size(); i++) {
        cout << res[i] << endl;
    }

    

    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值