Simple problem. The plain thought is to do the swap if there are two nodes, and do nothing if there is only one or no node left. Note to write the code as concise as possible, namely avoid excessive branches.
Solution:
# T:O(n) S:O(1) class Solution: # @param a ListNode # @return a ListNode def swapPairs(self, head): dummy = ListNode(0) dummy.next = head current = dummy while current.next and current.next.next: next_one, next_two, next_three = current.next, current.next.next, current.next.next.next current.next = next_two next_two.next = next_one next_one.next = next_three current = next_one return dummy.nextRun Time: 48 ms
No comments:
Post a Comment