Leetcode 24——Swap Nodes in Pairs

  

  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.

分析:调换每各pair中的两个node的位置,并返回新的首节点,不能直接改变node的值,而是要调整node的位置。这里要注意描述,调整pair中两个node的位置,返回新的首节点,一开始我只是调整完并没有返回新的首节点,结果几次报错都不知道为什么,明明调试出来的结果是正确的,看清题目很重要。其实这个题目的思路很简单,找到要调换的位置,然后调换一下就可以了,注意临界条件。先上我的代码。

public ListNode swapPairs(ListNode head) {
        if (head == null|| head.next == null)
            return head;
        ListNode finalHead=head.next;
        int index = 1;
        ListNode headBefore = null;
        ListNode headBeforeBefore = null;

        while (head!=null&&(head.next != null||(head.next==null&&headBefore.next!=null))) {
            if (index % 2 == 0) {
                //调换pair中的位置
                if(headBeforeBefore!=null)
                headBeforeBefore.next=head;
                
                headBefore.next=head.next;
                head.next=headBefore;
            
                                //调整新的head headB headBB的指代
                headBeforeBefore=head;
                head=headBefore.next;
                
                index++;
            }else {
                        //调整新的head headB headBB的指代
            headBeforeBefore = headBefore;
            headBefore = head;
            head=head.next;
            index++;
            }
        }

        return finalHead;
    }    

声明了两个节点,一个headB,一个headBB,代表head的父节点与head的祖父节点,然后index计数,每到2进行调换。其实后来想了一下,可以不用这样,在进行调换完成之后,直接定位到下一次要调换的位置,然后操作即可,这样会更快一点。每次调换之后,设置新的head、headB、headBB位置。

A掉之后看了别人的代码,简洁明了,用了递归。

public static ListNode swapPairs(ListNode head) {
        if(head==null||head.next==null) {
            return head;
        }
        ListNode n=head.next;
        head.next=swapPairs(head.next.next);
        n.next=head;
        return n;
    }

思路是设置完自身后,调用下一个要调换位置节点的方法。

原文地址:https://www.cnblogs.com/GoForMyDream/p/8533353.html