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.
这道题要求两两交换,其实就是五步法
step1: 寻找insert: ListNode insert = cur.next;
step2: 保存next: ListNode next = insert.next;
step3: 把insert插入到pre的后面: insert.next = pre.next; pre.next=insert;
step4: 连接断掉的部分(cur 和 next): cur.next = next;
step5: 更新pre和cur
public ListNode swapPairs(ListNode head) {
if(head==null)
return head;
ListNode helper = new ListNode(0);
helper.next=head;
ListNode pre = helper;
ListNode cur = head;
while(cur!=null&&cur.next!=null) {
ListNode insert = cur.next;
ListNode next = insert.next;
insert.next=pre.next;
pre.next=insert;
cur.next=next;
pre=cur;
cur=next;
}
return helper.next;
}