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
感覺自己應該要能寫得出來的,但第一次寫還是在 while loop 裡面有 nullpointerexception。這題的 while loop 條件得放在 prev.next != null && prev.next.next != null
public ListNode swapPairs(ListNode head) {
if (head == null) {
return head;
}
ListNode dummy = new ListNode(0);
ListNode prev = dummy;
dummy.next = head;
while (prev.next != null && prev.next.next != null) {
ListNode curr = prev.next;
ListNode next = prev.next.next;
curr.next = next.next;
prev.next = next;
prev.next.next = curr;
prev = prev.next.next;
}
return dummy.next;
}
另外有個 recursion 解法可以參考
public ListNode swapPairs(ListNode head) {
if ((head == null)||(head.next == null))
return head;
ListNode n = head.next;
head.next = swapPairs(head.next.next);
n.next = head;
return n;
}