directory

  • Topic describes
  • Thought analysis
  • AC code
  • conclusion

Nuggets team number online, help you Offer impromptu! Click for details

1. Title Description

Enter a linked list and return an ArrayList in the order from end to end.

Example 1

The input

,0,24,58 {67}

The return value

[58,24,0,67]

Second, train of thought analysis

Difficulty: More difficult

Print the linked list from end to end, but instead of returning a list to print, we return an array. We must avoid coding errors caused by unclear questions. There are generally two ways to solve this problem. The first way is to use recursive method, nesting calls to concatenate the current node, and finally get a join array from end to end. See method 1 for concrete implementation.

The second method is the general idea of taking an intermediate array and stitching it in reverse order to get the final destination array. This method is the easiest to think of and the easiest to understand. See method two for the concrete implementation.

AC code

Language: the Go

Methods a

Code:

package main
import . "nc_tools"
/* * type ListNode struct{ * Val int * Next *ListNode * } */

** @param head ListNode class * @return int 1 d array */
func printListFromTailToHead( head *ListNode ) []int {
    if head == nil {
        return []int{}}return append(printListFromTailToHead(head.Next), head.Val)
}
Copy the code

Method 2

Code:

package main
import . "nc_tools"
/* * type ListNode struct{ * Val int * Next *ListNode * } */

** @param head ListNode class * @return int 1 d array */
func printListFromTailToHead( head *ListNode ) []int {
    tmp := make([]int.0)
    res := make([]int.0)
    forhead ! =nil {
        tmp = append(tmp, head.Val)
        head = head.Next
    } 
    length := len(tmp)
    for length > 0 {
        res = append(res, tmp[length- 1])
        length--
    }
    return res
}
Copy the code

Through screenshots:

Method a,

Method 2,

Four,

This article introduces two of the most common methods, hoping to provide you with relevant ideas. Both methods have advantages and disadvantages. The former has small space complexity, while the latter has large space complexity, but the idea is simple.