1. Description
Given a linked list, swap every two adjacent nodes and return its head.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
2. Example
Given 1->2->3->4, you should return the list as 2->1->4->3.
3. Code
public class LeetCode0024 {
static class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public ListNode swapPairs(ListNode head)
{
ListNode dummy = new ListNode(0);
dummy.next = head;
swap(dummy);
return dummy.next;
}
private void swap(ListNode p1)
{
if (p1 == null) {
return;
}
ListNode p2 = p1.next;
if (p2 == null) {
return;
}
ListNode p3 = p2.next;
if (p3 == null) {
return;
}
p2.next = p3.next;
p3.next = p2;
p1.next = p3;
swap(p2);
}
}
Comments | NOTHING