-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3263-ConvertDoublyLinkedListToArrayI.go
More file actions
102 lines (90 loc) · 2.2 KB
/
3263-ConvertDoublyLinkedListToArrayI.go
File metadata and controls
102 lines (90 loc) · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package main
// 3263. Convert Doubly Linked List to Array I
// You are given the head of a doubly linked list,
// which contains nodes that have a next pointer and a previous pointer.
// Return an integer array which contains the elements of the linked list in order.
// Example 1:
// Input: head = [1,2,3,4,3,2,1]
// Output: [1,2,3,4,3,2,1]
// Example 2:
// Input: head = [2,2,2,2,2]
// Output: [2,2,2,2,2]
// Example 3:
// Input: head = [3,2,3,2,3,2]
// Output: [3,2,3,2,3,2]
// Constraints:
// The number of nodes in the given list is in the range [1, 50].
// 1 <= Node.val <= 50
import "fmt"
type Node struct {
Val int
Next *Node
Prev *Node
}
// 打印链表
func printListNode(l *Node) {
if nil == l {
return
}
for {
if nil == l.Next {
fmt.Print(l.Val)
break
} else {
fmt.Print(l.Val, " -> ")
}
l = l.Next
}
fmt.Println()
}
// 数组创建链表
func makeListNode(arr []int) *Node {
if (len(arr) == 0) {
return nil
}
l := len(arr) - 1
head := &Node{arr[l], nil, nil }
var pre *Node
for i := l - 1; i >= 0; i-- {
n := &Node{arr[i], head, pre}
head = n
pre = n
}
return head
}
/**
* Definition for a Node.
* type Node struct {
* Val int
* Next *Node
* Prev *Node
* }
*/
func toArray(head *Node) []int {
res := []int{}
for head != nil {
res = append(res, head.Val)
head = head.Next
}
return res
}
func main() {
// Example 1:
// Input: head = [1,2,3,4,3,2,1]
// Output: [1,2,3,4,3,2,1]
list1 := makeListNode([]int{1,2,3,4,3,2,1})
printListNode(list1) // 1 -> 2 -> 3 -> 4 -> 3 -> 2 -> 1
fmt.Println(toArray(list1)) // [1,2,3,4,3,2,1]
// Example 2:
// Input: head = [2,2,2,2,2]
// Output: [2,2,2,2,2]
list2 := makeListNode([]int{2,2,2,2,2})
printListNode(list2) // 2 -> 2 -> 2 -> 2 -> 2
fmt.Println(toArray(list2)) // [2,2,2,2,2]
// Example 3:
// Input: head = [3,2,3,2,3,2]
// Output: [3,2,3,2,3,2]
list3 := makeListNode([]int{3,2,3,2,3,2})
printListNode(list3) // 3 -> 2 -> 3 -> 2 -> 3 -> 2
fmt.Println(toArray(list3)) // [3,2,3,2,3,2]
}