美文网首页
24. Swap Nodes in Pairs

24. Swap Nodes in Pairs

作者: namelessEcho | 来源:发表于2017-09-24 18:57 被阅读0次

注意当结点交换之后 的迭代表达式不再是简单的next。next关系 ,特别是P1和P2。

class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head==null||head.next==null)return head;
        ListNode  dummy = new ListNode(0);
        dummy.next=head;
        ListNode p1 =head;
        ListNode p2 = head.next;
        ListNode p3 = head.next.next;
        ListNode pre = dummy ; 
        int count =0;
        while(true)
        {
            p2.next=p1;
            p1.next=p3;
            pre.next=p2;
            if(p3==null||p3.next==null)
                break;
            else
                p3=p3.next.next;
            pre=pre.next.next;
            p1=p1.next;
            p2=p2.next.next.next;
        }
        return dummy.next;
    }
}

相关文章

网友评论

      本文标题:24. Swap Nodes in Pairs

      本文链接:https://www.haomeiwen.com/subject/fkqlextx.html