24. Swap Nodes in Pairs
2016-12-20 本文已影响2人
hyhchaos
Java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode swapPairs(ListNode head) {
if(head==null) return null;
if(head.next==null) return head;
ListNode tmp=head.next;
ListNode nt=head;
head=head.next;
while(nt.next!=null&&tmp.next!=null)
{
ListNode v=tmp.next.next;
ListNode w=tmp.next;
tmp.next=nt;
if(v!=null)
{
nt.next=v;
tmp=v;
nt=w;
}
else
{
nt.next=w;
nt=w;
}
}
if(nt.next==null)
return head;
tmp.next=nt;
nt.next=null;
return head;
}
}
优解,Java,方法差不多,但在head节点之前添加一个节点的做法很nice
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode current = dummy;
while (current.next != null && current.next.next != null) {
ListNode first = current.next;
ListNode second = current.next.next;
first.next = second.next;
current.next = second;
current.next.next = first;
current = current.next.next;
}
return dummy.next;
}