TreeviewCopyright © aleen42 all right reserved, powered by aleen42

06. 从尾到头打印链表

https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/

Java

/*
 * @Author: Goog Tech
 * @Date: 2020-07-16 17:42:14
 * @Description: https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/
 * @FilePath: \leetcode-googtech\剑指 Offer\#06. 从尾到头打印链表\Solution.java
 */ 

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public int[] reversePrint(ListNode head) {
        // 首先遍历链表来获取链表的长度值
        ListNode currentNode = head;
        int len = 0;
        while(currentNode!=null){
            len++;
            currentNode = currentNode.next;
        }
        // 其次倒叙遍历链表并将节点逐个插入数组
        currentNode = head;
        int [] result = new int[len];
        for(int i = len - 1;i >=0; i--){
            result[i] = head.val;
            head = head.next;
        }
        return result;
    }
}

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

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

限制:
0 <= 链表长度 <= 10000
*/

Python

'''
@Author: Goog Tech
@Date: 2020-07-16 17:42:24
@Description: https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/
@FilePath: \leetcode-googtech\剑指 Offer\#06. 从尾到头打印链表\Solution.py
'''

# 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):
        """
        :type head: ListNode
        :rtype: List[int]
        """
        # 初始化栈
        stack = []
        # 入栈
        while head:
            stack.append(head.val)
            head = head.next
        result = []
        # 出栈
        while stack:
            result.append(stack.pop())
        return result

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

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

限制:
0 <= 链表长度 <= 10000
"""
Copyright © GoogTech 2021 all right reserved,powered by GitbookLast update time : 2021-09-15 01:55:05

results matching ""

    No results matching ""