交换链表中相邻的元素

成对交换链表中相邻的元素

方法一:

直接交换链表中两个元素值,给元素交换赋值,而不用改变指针方向;但是这种方法中当单个节点中有很多字段的时候(比如:name,age,sex),效率较低!

package suanfa.warppairs;



/**
 * @description:两两交换链表中相邻节点
 * 通过直接交换元素值,不改变指针方向的方式,需要辅助空间O(1)
 * @author: fangct
 * @create: 2019-01-24 10:55
 * */
public class SwapPairsNodes {
    public static void main(String[] args) {
        MyNode head = new MyNode(1,new MyNode(2,new MyNode(3,new MyNode(4,new MyNode(5,new MyNode(6,null))))));
        MyNode resultNode  = swapPairs(head);
        printNode(resultNode);
    }

    /**
     * 交换逻辑
     * @param head
     * @return
     */
    public static MyNode swapPairs(MyNode head) {
        if(head == null || head.next == null)
            return head;

        MyNode A = head;
        MyNode B = head.next;

        int t;
        while(A != null && B != null){
            t = B.val;
            B.val = A.val;
            A.val = t;

            if(B.next == null)
                break;
            A = B.next;
            B = B.next.next;
        }

        return head;
    }

    public static void printNode(MyNode head) {
        while (head!= null) {
            System.out.println(head.val);
            head =head.next;
        }
    }
}
class MyNode{
    int val;
    MyNode next;

    public MyNode(int val) {
        this.val = val;
    }

    public MyNode(int val, MyNode next) {
        this.val = val;
        this.next = next;
    }
}

方法二:

通过改变指针方向,来交换元素

package suanfa.warppairs;

/**
 * @description:成对交换两个链表中相邻两个元素
 * @author: fangct
 * @create: 2019-01-24 10:19
 * */
public class SwapPairs {
    public static void main(String[] args) {
        Node head = new Node(1,new Node(2,new Node(3,new Node(4,new Node(5,new Node(6,null))))));
        Node resultNode  = swarpNodePairs(head);
        printNode(resultNode);
    }

    public static Node swarpNodePairs(Node head) {
        Node dummy = new Node(0);
        dummy.next = head; //给结果链表一个头结点0->1->2->3->4->5->6
        Node current = dummy; //将新的结果链表复制一份
        while (current.next != null && current.next.next != null) {
            Node first = current.next;
            Node second = current.next.next;
            first.next = second.next;//1-> [3->4->5->6]
            current.next = second; //0->2->[3->4->5->6]
            current.next.next = first;//0->2->1-> [3->4->5->6]
            //向后走两步:current -》3
            current = current.next.next;
        }
        return dummy.next;
    }

    public static void printNode(Node head) {
        while (head!= null) {
            System.out.println(head.val);
            head =head.next;
        }
    }


}

class Node{
    int val;
    Node next;

    public Node(int val) {
        this.val = val;
    }

    public Node(int val, Node next) {
        this.val = val;
        this.next = next;
    }
}




最终结果:2,1,4,3,6,5

猜你喜欢

转载自blog.csdn.net/fct2001140269/article/details/86622869