美文网首页
24. Swap Nodes in Pairs

24. Swap Nodes in Pairs

作者: hyhchaos | 来源:发表于2016-12-20 19:46 被阅读2次

    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;
    }
    

    相关文章

      网友评论

          本文标题:24. Swap Nodes in Pairs

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