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.
解:处理每一对时,先断开与其后的联系再处理。此外,重新排序的时候防止互锁。
public ListNode swapPairs(ListNode head) {
ListNode first = null; //待交换对的第一个
ListNode second = null; //待交换对的第二个
ListNode temp = null; //临时存储下一个交换对的第一个
ListNode end = null; //已交换对的最后一个
ListNode result = null; //用于记录链表起始位置
//为空或只有一个元素 直接返回
if (head == null || head.next==null) return head;
first = head;
second = head.next;
result = second;
while (first != null && second != null){
temp = first.next.next;
//记得先断开first对second的指针 否则容易相互指向而互锁
first.next = null;
second.next = first;
//上一对的末尾指向这一对的开始
if (end != null) end.next = second;
end = first;
first = temp;
if (temp == null){
break;
}
second = temp.next;
}
if (first != null) end.next = first;
return result;
}