描述:
Given1->2->3->4
, you should return the list as2->1->4->3
需要运用fakehead来指向原指针头,防止丢链,用两个指针,ptr1始终指向需要交换的pair的前面一个node,ptr2始终指向需要交换的pair的第一个node。
需要用一个临时指针nextstart, 指向下一个需要交换的pair的第一个node,保证下一次交换的正确进行。
当链表长度为奇数时,ptr2.next可能为null;
当链表长度为偶数时,ptr2可能为null。
所以把这两个情况作为终止条件,在while判断就好,最后返回fakehead.next
写的时候怎么想都不对,后面看了下别人的答案,嗯,有点绕,懂了就好了
public static ListNode swapPairs(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode fakehead = new ListNode(-1);
fakehead.next = head;
ListNode first = fakehead.next;
ListNode second = fakehead;
while (first != null && first.next != null) {
ListNode tmp = first.next.next;//保存后面的
first.next.next = first;//2指向 1
second.next = first.next;//把1 指向 2
first.next = tmp;//把 1 与 2 断开, 指向后面的一串
//后移动
second = first;
first = first.next;
}
return fakehead.next;
}
下图是一次分析结果,自己画下还是很好懂的
递归这种神仙操作,现在还想不到...
public ListNode swapPairs(ListNode head) {
if(head == null){
return null;
}
if(head.next == null){
return head;
}
ListNode temp = head.next; //保留后续链表
head.next = swapPairs(temp.next);
temp.next = head; //交换
return temp;
}