前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >剑指Offer - 面试题6. 从尾到头打印链表(栈,递归,反转链表)

剑指Offer - 面试题6. 从尾到头打印链表(栈,递归,反转链表)

作者头像
Michael阿明
发布2020-07-13 17:32:57
2300
发布2020-07-13 17:32:57
举报

1. 题目

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

代码语言:javascript
复制
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
 
限制:
0 <= 链表长度 <= 10000

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. 解题

2.1 stack解题

代码语言:javascript
复制
class Solution {
public:
    vector<int> reversePrint(ListNode* head) {
        stack<int> s;
        while(head)
        {
        	s.push(head->val);
        	head = head->next;
        }
        vector<int> ans;
        while(!s.empty())
        {
        	ans.push_back(s.top());
        	s.pop();
        }
        return ans;
    }
};
在这里插入图片描述
在这里插入图片描述

2.2 递归

代码语言:javascript
复制
class Solution {
	vector<int> ans;
public:
    vector<int> reversePrint(ListNode* head) {
        dfs(head);
        return ans;
    }

    void dfs(ListNode* head)
    {
    	if(!head)
    		return;
    	dfs(head->next);
    	ans.push_back(head->val);
    }
};
在这里插入图片描述
在这里插入图片描述

2.3 反转链表

代码语言:javascript
复制
class Solution {
	vector<int> ans;
public:
    vector<int> reversePrint(ListNode* head) {
    	if(!head)
    		return {};
        head = reverseList(head);
        while(head)
        {
        	ans.push_back(head->val);
        	head = head->next;
        }
        return ans;
    }

	ListNode* reverseList(ListNode* head)
	{	//反转链表,返回新表头
		ListNode *prev = NULL, *nt = head->next;
		while(head && head->next)
		{
			head->next = prev;
			prev = head;
			head = nt;
			nt = nt->next;
		}
		head->next = prev;
		return head;
	}    
};
在这里插入图片描述
在这里插入图片描述
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-02-12 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 题目
  • 2. 解题
    • 2.1 stack解题
      • 2.2 递归
        • 2.3 反转链表
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档