剑指offer 从尾到头打印链表

本文介绍五种不同的方法实现链表从尾到头的打印,包括使用栈、vector及递归等技术,并提供了详细的C++代码示例。

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

题目描述

输入一个链表,从尾到头打印链表每个节点的值。

思路

总共有五种方法,如下:
1. 将原链表的值存在一个栈中,然后再将栈输出到另一个vector数组里。
2. 直接将原链表的值存在一个vector数组里,最后reverse翻转一下。
3. 每插入一个,都放到最前面,复杂度是n2,不是很高效。
4. 通过递归到最后一个值,再一层一层输入到vector数组里。
5. 直接将链表翻转。

代码
  1. 1.
class Solution {
public:
  vector<int>printListFromTailToHead(ListNode*head) {
        int digit;
        stack<int> f;
        vector<int> res;
        ListNode *t = head;
        while(t != NULL)
        {
            f.push(t->val);
            t = t->next;
        }
        while(!f.empty())
        {
            digit = f.top();
            f.pop();
            res.push_back(digit);
        }
        return res;
    }
};
  1. 2.
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> res;
        while(head != NULL)
        {
            res.push_back(head->val);
            head = head->next;
        }
        reverse(res.begin(),res.end());
        return res;
    }
};
  1. 3.
class Solution {
public:
    vector<int> printListFromTailToHead(struct ListNode* head) {
        vector<int> res;
        if(head != NULL)
        {
            while(head != NULL)
            {    
               res.insert(res.begin(),head->val);
               head = head->next;
            }                      
        }
        return res;
    }
};
  1. 4.
class Solution {
public:
    vector<int> res;
    vector<int> printListFromTailToHead(ListNode* head) {
        if(head!=NULL){
            printListFromTailToHead(head->next);
            res.push_back(head->val);
        }
        return res;
    }
};
  1. 5.
class Solution {
public:
   vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> res;
        ListNode *pre = NULL;
        ListNode *p = NULL;
        while(head != NULL)
        {
            p = head->next; //p为head的下一个节点
            head->next = pre;//指向前一个节点
            pre = head;//向后移动
            head = p;//向后移动
        }
        while(pre != NULL)
        {
            res.push_back(pre->val);
            pre = pre->next;
        }
       return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值