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 class A24SwapNodesinPairs {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null)
return head;
ListNode beforeHead = new ListNode(0);
beforeHead.next = head;
ListNode first = beforeHead;
ListNode second = beforeHead.next;
ListNode third = head.next;
while(third != null) {
first.next = third;
second.next = third.next;
third.next = second;
first = second;
second = second.next;
if(second == null)
break;
third = second.next;
}
return beforeHead.next;
}
}
后来看到一个递归写法,膜拜.
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode temp = head.next;
head.next = swapPairs(temp.next);
temp.next = head;
return temp;
}