题目描述:给定一个链表,每交换两个相邻节点并返回其头部。
您不能修改列表节点中的值,只能修改节点本身。
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
public static ListNode swapPairs(ListNode head) {
if ((head == null) || (head.next == null))
return head;
ListNode Next = head.next;
head.next = swapPairs(head.next.next);
Next.next = head;
return Next;
}
public static ListNode swapPairs2(ListNode head) {
if (head == null)
return null;
ListNode helper = new ListNode(0);
helper.next = head;
ListNode pre = helper;
ListNode cur = head;
while (cur != null && cur.next != null) {
ListNode next = cur.next.next;
cur.next.next = cur;
pre.next = cur.next;
if (next != null && next.next != null)
cur.next = next.next;
else
cur.next = next;
pre = cur;
cur = next;
}
return helper.next;
}