-
Notifications
You must be signed in to change notification settings - Fork 215
/
Copy pathMedium_024_Swap_Nodes_In_Pairs.swift
46 lines (36 loc) · 1.19 KB
/
Medium_024_Swap_Nodes_In_Pairs.swift
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
/*
https://leetcode.com/problems/swap-nodes-in-pairs/
#24 Swap Nodes in Pairs
Level: medium
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
Inspired by @mike3 at https://leetcode.com/discuss/3608/seeking-for-a-better-solution
*/
import Foundation
class Medium_024_Swap_Nodes_In_Pairs {
class Node {
var value: Int
var next: Node?
init(value: Int, next: Node?) {
self.value = value
self.next = next
}
}
class func swap(next1: Node, next2: Node) -> Node {
next1.next = next2.next
next2.next = next1
return next2
}
class func swapPairs(_ head: Node?) -> Node? {
let dummy: Node = Node(value: 0, next: nil)
dummy.next = head
var curr: Node? = dummy
while curr?.next != nil && curr?.next?.next != nil {
curr?.next = swap(next1: curr!.next!, next2: curr!.next!.next!)
curr = curr?.next?.next
}
return dummy.next
}
}