题目:
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.
解题:每一次处理两个节点,对节点的指针进行交换。这里说明一下交换流程:
1,记录下一次需要遍历的节点(在后面操作中会改变指向,如不记录链表会断裂)next=curr.next;
2,使第二个节点指向第一个节点。curr.next=pre.next;
3,使表头指向第二个节点。pre.next=curr;这时候pre->节点2->节点1
4,移动pre指针到节点1。pre=cur;
5,使pre的next指向下一次需要进行处理的第一个节点。pre.next=next;
6,cur指针移动到下一次需要进行处理的第一个节点。cur=next;
代码:
public static ListNode swapPairs(ListNode head) {
if(head==null||head.next==null)
return head;
ListNode fakeNode=new ListNode(-1);
fakeNode.next=head;
ListNode pre=fakeNode,cur=head,next=null,curr=null;
while(cur!=null&&cur.next!=null)
{
curr=cur.next;//用一个变量记录,在后面调用中减少多次节点二重指向,能够减少运行时间
next=curr.next;
curr.next=pre.next;
pre.next=curr;
pre=cur;
pre.next=next;
cur=next;
}
return fakeNode.next;
}