-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path143.重排链表.go
53 lines (49 loc) · 838 Bytes
/
143.重排链表.go
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
/*
* @lc app=leetcode.cn id=143 lang=golang
*
* [143] 重排链表
*/
// @lc code=start
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func findMid(head *ListNode) *ListNode {
slow := head
fast := head.Next
for fast!=nil && fast.Next != nil {
fast = fast.Next.Next
slow = slow.Next
}
return slow
}
func reverseList(head *ListNode) *ListNode {
var prev *ListNode
for head != nil {
tmp := head.Next
head.Next= prev
prev= head
head = tmp
}
return prev
}
func reorderList(head *ListNode) {
if head == nil {
return
}
dummy1 := head
mid := findMid(head)
secondHalf := mid.Next
l2 := reverseList(secondHalf)
mid.Next = nil
for dummy1 != nil {
tmp := dummy1.Next
dummy1.Next = l2
l2 = tmp
dummy1 = dummy1.Next
}
}
// @lc code=end