欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Swap Nodes in Pairs

程序员文章站 2022-03-05 08:09:29
...

Given a linked list, swap every two adjacent nodes and return its head.

You may not modify the values in the list’s nodes, only nodes itself may be changed.

Example:

Given 1->2->3->4, you should return the list as 2->1->4->3.

 /**
     * 递归的两种方法
     * @param head
     * @return
     */
    public static Node SwapNodeByRecursion1(Node head)
    {
        if(head == null || head.next == null)
            return head;
        Node n = head.next;
        head.next = SwapNodeByRecursion1(head.next.next);
        n.next = head;
        return n;
    }
    public Node swapPairsByRecursion2(Node head) {
        if (head == null || head.next == null) return head;
        Node second = head.next;
        Node third = second.next;

        second.next = head;
        head.next = swapPairsByRecursion2(third);

        return second;
    }

    /**
     * 使用迭代的方法
     * @param head
     * @return
     */
    public static Node swapPairsByIterator(Node head)
    {
        if(head == null || head.next == null) return head;
        Node newHead = head.next,a = head,b = a.next,pre = null;
        while(a!=null || b!= null)
        {
            a.next = b.next;
            b.next = a;
            if(pre != null) pre.next =b;
            if(a.next == null) break;
            b = a.next.next;
            pre = a;
            a = a.next;
        }
        return newHead;
    }