24. Swap Nodes in Pairs (Medium)
https://leetcode.com/problems/swap-nodes-in-pairs/
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example:
Given1->2->3->4
, you should return the list as2->1->4->3
.
Solutions
class Solution {
// To make it easy, it is strongly recommended to prepend a dummy node as the 'head' of the list.
public ListNode swapPairs(ListNode head) {
if (head == null) {
return null;
}
if (head.next == null) {
return head;
}
// Create a dummy head node to lead the list, which facilitates the swapping operation.
ListNode dummy = new ListNode(0);
dummy.next = head;
// p1->p2->p3; p2 and p3 are nodes being swapped
ListNode p1 = dummy;
ListNode p2 = p1.next;
ListNode p3 = p2.next;
// examples: -1->1->2->3; -1->1->2
while (p3 != null) {
p2.next = p3.next;
p3.next = p2;
p1.next = p3;
p1 = p2;
if (p1.next == null) {
break;
}
p2 = p1.next;
p3 = p2.next;
}
return dummy.next;
}
}