剑指Offer - 面试题6. 从尾到头打印链表(栈,递归,反转链表)
发布日期:2021-07-01 03:20:06 浏览次数:2 分类:技术文章

本文共 1441 字,大约阅读时间需要 4 分钟。

文章目录

1. 题目

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

示例 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解题

class Solution {
public: vector
reversePrint(ListNode* head) {
stack
s; while(head) {
s.push(head->val); head = head->next; } vector
ans; while(!s.empty()) {
ans.push_back(s.top()); s.pop(); } return ans; }};

在这里插入图片描述

2.2 递归

class Solution {
vector
ans;public: vector
reversePrint(ListNode* head) {
dfs(head); return ans; } void dfs(ListNode* head) {
if(!head) return; dfs(head->next); ans.push_back(head->val); }};

在这里插入图片描述

2.3 反转链表

class Solution {
vector
ans;public: vector
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; } };

在这里插入图片描述

转载地址:https://michael.blog.csdn.net/article/details/104272440 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:剑指Offer - 面试题9. 用两个栈实现队列
下一篇:剑指Offer - 面试题5. 替换空格(字符串)

发表评论

最新留言

很好
[***.229.124.182]2024年04月24日 22时22分10秒