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.
思路:利用两个置换,be指向前一个node,af指向后一个node
代码:
public ListNode swapPairs(ListNode head) { if(head==null ||head.next==null) return head; ListNode node=new ListNode(0); node.next=head; ListNode temp=node,be=head,af=head.next; while(true) { //node置换 temp.next=af; be.next=af.next; af.next=be; //af,be置换 temp=af; af=be; be=temp; temp=af; //指针重置 be=af.next; if(be==null)break; af=be.next; if(af==null)break; } return node.next; }