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

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

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

实例:

输入 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);
    }
}

输出结果是:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值