-
Notifications
You must be signed in to change notification settings - Fork 0
/
swap-nodes-in-pairs.go
48 lines (38 loc) · 952 Bytes
/
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
package main
import (
"fmt"
. "github.com/dimaglushkov/solutions/ADS/list"
)
// source: https://leetcode.com/problems/swap-nodes-in-pairs/
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func swapPairs(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
res := new(ListNode)
res.Next = head
prev := res
for head != nil && head.Next != nil {
head.Next, head.Next.Next, prev.Next = head.Next.Next, prev.Next, head.Next
prev = head
head = head.Next
}
return res.Next
}
func main() {
// Example 1
var head1 *ListNode = NewList([]int{1, 2, 3, 4})
fmt.Println("Expected: [2,1,4,3] Output: ", swapPairs(head1))
// Example 2
var head2 *ListNode = NewList([]int{})
fmt.Println("Expected: [] Output: ", swapPairs(head2))
// Example 3
var head3 *ListNode = NewList([]int{1})
fmt.Println("Expected: [1] Output: ", swapPairs(head3))
}