|
@@ -0,0 +1,79 @@
|
|
|
|
+package main
|
|
|
|
+
|
|
|
|
+import "fmt"
|
|
|
|
+
|
|
|
|
+func main() {
|
|
|
|
+ var vals []int
|
|
|
|
+
|
|
|
|
+ vals = []int{}
|
|
|
|
+ printList(swapPairs(createList(vals)))
|
|
|
|
+
|
|
|
|
+ vals = []int{1}
|
|
|
|
+ printList(swapPairs(createList(vals)))
|
|
|
|
+
|
|
|
|
+ vals = []int{1, 2}
|
|
|
|
+ printList(swapPairs(createList(vals)))
|
|
|
|
+
|
|
|
|
+ vals = []int{1, 2, 3}
|
|
|
|
+ printList(swapPairs(createList(vals)))
|
|
|
|
+
|
|
|
|
+ vals = []int{1, 2, 3, 4}
|
|
|
|
+ printList(swapPairs(createList(vals)))
|
|
|
|
+
|
|
|
|
+ vals = []int{1, 2, 3, 4, 5}
|
|
|
|
+ printList(swapPairs(createList(vals)))
|
|
|
|
+
|
|
|
|
+ vals = []int{1, 2, 3, 4, 5, 6}
|
|
|
|
+ printList(swapPairs(createList(vals)))
|
|
|
|
+
|
|
|
|
+ vals = []int{1, 2, 3, 4, 5, 6, 7}
|
|
|
|
+ printList(swapPairs(createList(vals)))
|
|
|
|
+}
|
|
|
|
+
|
|
|
|
+//Definition for singly-linked list.
|
|
|
|
+type ListNode struct {
|
|
|
|
+ Val int
|
|
|
|
+ Next *ListNode
|
|
|
|
+}
|
|
|
|
+
|
|
|
|
+func createList(vals []int) *ListNode {
|
|
|
|
+ var head, list *ListNode
|
|
|
|
+ for _, v := range vals {
|
|
|
|
+ if head == nil {
|
|
|
|
+ list = &ListNode{Val: v, Next: nil}
|
|
|
|
+ head = list
|
|
|
|
+ continue
|
|
|
|
+ }
|
|
|
|
+ var temp = &ListNode{Val: v, Next: nil}
|
|
|
|
+ list.Next = temp
|
|
|
|
+ list = list.Next
|
|
|
|
+ }
|
|
|
|
+ return head
|
|
|
|
+}
|
|
|
|
+
|
|
|
|
+func printList(node *ListNode) {
|
|
|
|
+ var temp = node
|
|
|
|
+ for temp != nil {
|
|
|
|
+ fmt.Printf("%d", temp.Val)
|
|
|
|
+ if temp.Next != nil {
|
|
|
|
+ fmt.Printf("%s", "->")
|
|
|
|
+ }
|
|
|
|
+ temp = temp.Next
|
|
|
|
+ }
|
|
|
|
+ fmt.Println()
|
|
|
|
+}
|
|
|
|
+
|
|
|
|
+func swapPairs(head *ListNode) *ListNode {
|
|
|
|
+ var cursor = &ListNode{Val: 0, Next: head}
|
|
|
|
+ var neaHead = cursor
|
|
|
|
+ var temp *ListNode
|
|
|
|
+ for cursor.Next != nil && cursor.Next.Next != nil {
|
|
|
|
+ temp = cursor.Next
|
|
|
|
+ cursor.Next = temp.Next
|
|
|
|
+ temp.Next = temp.Next.Next
|
|
|
|
+ cursor.Next.Next = temp
|
|
|
|
+
|
|
|
|
+ cursor = cursor.Next.Next
|
|
|
|
+ }
|
|
|
|
+ return neaHead.Next
|
|
|
|
+}
|