题目:
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
思路:
三个指针
Code1:
public ListNode swapPairs(ListNode head) {
if(head==null || head.next==null) return head;
ListNode cur=head, post=cur.next;
cur.next=post.next;
post.next=cur;
head=post;
ListNode pre=cur;
cur=cur.next;
while(cur!=null && post!=null){
post=cur.next;
if(post!=null){
pre.next=post;
cur.next=post.next;
post.next=cur;
pre=cur;
cur=cur.next;
}else{
break;
}
}
return head;
}
备注:
三个指针换