剑指 Offer 06. 从尾到头打印链表🌟🌟🌟🌟🌟简单

课后作业

问题描述

原文链接:剑指 Offer 06. 从尾到头打印链表

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

示例 1:

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

限制:

0 <= 链表长度 <= 10000

代码实现

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) {
        if(head == null){
            return new int[0];
        }

        int n = 0;
        ListNode temp = head;
        while(temp != null){
            n++;
            temp = temp.next;
        }
        int res[] = new int[n];
        while(head != null){
            res[--n] = head.val;
            head = head.next;
        }

        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):
        """
        :type head: ListNode
        :rtype: List[int]
        """
        if head == None:
            return []

        n = 0
        temp = head
        while temp != None:
            n += 1
            temp = temp.next
        res = [0]*n
        while head != None:
            n -= 1
            res[n] = head.val
            head = head.next

        return 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) {
        if (head == NULL) {
            return vector<int>();
        }

        int n = 0;
        ListNode* temp = head;
        while (temp != NULL) {
            n++;
            temp = temp->next;
        }

        vector<int> res(n);
        while (head != NULL) {
            n--;
            res[n] = head->val;
            head = head->next;
        }

        return res;
    }
};

Go

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func reversePrint(head *ListNode) []int {
    if head == nil {
        return []int{}
    }

    n := 0
    temp := head
    for temp != nil {
        n++
        temp = temp.Next
    }

    res := make([]int, n)
    for head != nil {
        n--
        res[n] = head.Val
        head = head.Next
    }

    return res
}

发表评论

后才能评论