2020 P7阿里机试题 一个链表,两两交换其中相邻的节点,并返回交换后的链表

题目是给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。

你不能只是单纯的改变借电内部的值,而是需要实际的进行节点交换。

实例:

输入 1->2->3->4,你返回2->1->4->3.

方法1:

public class test2 {
    static class Node{
       public Integer value;
       public Node nextNode;


    }

    public Node reser(Node node){


        Node newNode = null;

        Node returnNode = null;

        Node preNode = null;

        do {
            Node jiao1 = node;
            Node jiao2 = node.nextNode;

            Node node1 = new Node();
            node1.value = jiao2.value;
            newNode = node1;

            Node node2 = new Node();
            node2.value = jiao1.value;

            newNode.nextNode = node2;

            if(returnNode == null){
                returnNode = newNode;
            }else{
                preNode.nextNode = newNode;
            }

            node = jiao2.nextNode;
            preNode = node2;
        }while (node!=null);

        return returnNode;
    }



    public Node reser2(Node node){
        Node returnNode = null;
        Node nextNode = null;
        Node preNode = null;
        do {

            Node node2 = node.nextNode;
            nextNode = node.nextNode.nextNode;
            Node node1 = node;
           if(preNode !=null){
               preNode.nextNode = node2;
           }
           node2.nextNode = node1;
           node1.nextNode = nextNode;
           if(returnNode == null){
               returnNode = node2;
           }

           preNode = node1;
           node = nextNode;
        }while (node!=null);

        return returnNode;
    }

    public static void main(String[] args) {
        test2 t = new test2();

        Node node = new Node();
        node.value = 1;
        Node node2 = new Node();
        node2.value = 2;
        Node node3 = new Node();
        node3.value = 3;
        Node node4 = new Node();
        node4.value = 4;
        node.nextNode = node2;
        node2.nextNode = node3;
        node3.nextNode = node4;



        Node returnNode = t.reser2(node);
        System.out.println(returnNode);
    }
}

输出结果是:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章