LeetCode #24 Swap Nodes in Pairs
LeetCode #24 Swap Nodes in Pairs
Question
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.
Solution
Approach #1
/**
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init(_ val: Int) {
* self.val = val
* self.next = nil
* }
* }
*/
class Solution {
func swapPairs(_ head: ListNode?) -> ListNode? {
let dummy = ListNode(0)
dummy.next = head
var p1: ListNode? = dummy
var p2 = p1?.next
while p2?.next != nil {
p1?.next = p2?.next
p2?.next = p2?.next?.next
p1?.next?.next = p2
p1 = p1?.next?.next
p2 = p1?.next
}
return dummy.next
}
}
Time complexity: O(n).
Space complexity: O(1).
转载请注明出处:http://www.cnblogs.com/silence-cnblogs/p/7066019.html