0
点赞
收藏
分享

微信扫一扫

【剑指Offer】06. 从尾到头打印链表 解题报告(Java & python)



  • 作者: 负雪明烛
  • id: fuxuemingzhu
  • 个人博客:​​http://fuxuemingzhu.cn/​​


目录


  • ​​题目描述​​
  • ​​解题方法​​

  • ​​栈​​
  • ​​递归​​
  • ​​数组​​

  • ​​日期​​



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

题目描述

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

示例 1:

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

限制:

  • ​0 <= 链表长度 <= 10000​

解题方法

从尾到头打印链表,可以用 ​栈、递归​ 两种方法解决。还有一种最笨的方法:先从头到尾遍历链表放到数组中,最后再把数组进行翻

当使用额外空间时,从尾到头的顺序恰恰与栈的「​后进先出​」的顺序非常吻合。


  1. 从头到尾遍历一次链表,使用「栈」来存储链表的每个的值;
  2. 出栈的时候,得到的就是链表每个节点 ​从尾到头​ 的顺序。

C++ 代码如下:

/**
* 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) {
stack<int> st;
while (head) {
st.push(head->val);
head = head->next;
}
vector<int> res;
while (!st.empty()) {
res.push_back(st.top());
st.pop();
}
return res;
}
};

Python 代码如下:

# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution(object):
def reversePrint(self, head):
res = collections.deque()
while head:
res.appendleft(head.val)
head = head.next
return list(res)

递归

在程序上「栈」与「递归」是对应的,因为「递归」底层就是利用了系统的「栈」实现的。这题如果不声明一个「栈」的变量的时候,则可以使用系统「栈」,即使用递归。

「从尾到头」打印链表,类似于树的「​后序遍历​」,所以在代码中需要先调用递归函数,再把当前节点的值放到 ​​res​​ 中。即:

reverse(head->next);
res.push_back(head->val);

上面这两句的顺序不可以反,如果反过来,那么就类似于树的「先序遍历」,得到的是「​从头到尾​」打印链表。

C++ 代码如下:

/**
* 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) {
res.clear();
reverse(head);
return res;
}
void reverse(ListNode* head) {
if (!head)
return;
reverse(head->next);
res.push_back(head->val);
}
private:
vector<int> res;
};

数组

该做法是从头到尾把链表遍历一次,遍历的结果放到数组中。最后再把数组进行翻

C++ 代码如下:

/**
* 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> res;
while (head) {
res.push_back(head->val);
head = head->next;
}
reverse(res.begin(), res.end());
return res;
}
};

Python 代码如下:

# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution(object):
def reversePrint(self, head):
res = []
while head:
res.append(head.val)
head = head.next
return res[::-1]

日期

2017 年 4 月 20 日

2018 年 3 月 9 日

2021 年 7 月 31 日 —— 下周就要离职了



举报

相关推荐

0 条评论