Description:
Given a linked list, swap every two adjacent nodes and return its head.
Solution:
We can get two list nodes each time, then just simply switch them. Remember that there are three 'next' links need to be changed, in addition to the two list nodes here, also the one before the first one.
public class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode first, second, tot;
first = head;
second = first.next;
first.next = second.next;
second.next = first;
head = second;
tot = first;
while (tot.next != null) {
first = tot.next;
second = first.next;
if (second == null) {
break;
} else {
tot.next = second;
first.next = second.next;
second.next = first;
tot = first;
}
}
return head;
}
}