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.
这道题还算简单,我用的是迭代。public ListNode swapPairs(ListNode head) {
if(head==null||head.next==null){
return head;
}
ListNode newHead=head.next;
ListNode node=head;
while(node!=null&&node.next!=null){
ListNode tmp=node.next.next;
node.next.next=node;
node.next=tmp;//保证tmp=null或者tmp.next=null的情况能考虑到
if(tmp!=null&&tmp.next!=null){
node.next=tmp.next;
}
node=tmp;
}
return newHead;
}
有大神用的是递归做的,很是简洁。
My solution is quite simple. Just find the reverse job is the same for every 2 nodes.
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newhd = head.next;
head.next = swapPairs(newhd.next);
newhd.next = head;
return newhd;
}