-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathswap-nodes-in-pairs.go
52 lines (47 loc) · 1.03 KB
/
swap-nodes-in-pairs.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
package main
import (
"fmt"
)
type ListNode struct {
Val int
Next *ListNode
}
func (head *ListNode) String() string {
list := ""
for temp := head; temp != nil; temp = temp.Next {
if temp == head {
list = fmt.Sprintf("%d", temp.Val)
} else {
list = fmt.Sprintf("%s->%d", list, temp.Val)
}
}
return list
}
func swapPairs(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
if head != nil && head.Next != nil {
next := head.Next
head.Next = next.Next
next.Next = head
head = next
}
for previous, current := head.Next, head.Next.Next; previous != nil && current != nil && current.Next != nil; {
next := current.Next
previous.Next = next
if next != nil {
current.Next = next.Next
next.Next = current
}
previous = current
current = current.Next
}
return head
}
func main() {
list := &ListNode{1, &ListNode{2, &ListNode{3, &ListNode{4, &ListNode{5, nil}}}}}
fmt.Println(swapPairs(list))
list = &ListNode{1, &ListNode{2, &ListNode{3, nil}}}
fmt.Println(swapPairs(list))
}