zoukankan      html  css  js  c++  java
  • leetcode 24. 两两交换链表中的节点

    /**
     * @Class Swap
     * @Description 24. 两两交换链表中的节点
     *  给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。 
     *
     *  你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。 
     *
     *  示例 1: 
     * 输入:head = [1,2,3,4]
     * 输出:[2,1,4,3]
     *  示例 2: 
     * 输入:head = []
     * 输出:[]
     *  示例 3: 
     * 输入:head = [1]
     * 输出:[1]
     *
     *  提示: 
     *  链表中节点的数目在范围 [0, 100] 内 
     *  0 <= Node.val <= 100 
     *
     * @Author Administrator
     * @Date 2020/12/2 21:15
     **/
    public class Swap {
        static class ListNode {
            private int value;
            private ListNode next;
    
            public ListNode(int value) {
                this.value = value;
                next = null;
            }
        }
    
        /*
         * 递归
         */
        public static ListNode getReverse(ListNode head) {
            if (head == null || head.next == null) return head;
            ListNode newNode = head.next;
            head.next = getReverse(head.next.next);
            newNode.next = head;
            return newNode;
        }
    
        public static void main(String[] args) {
            ListNode head = new ListNode(1);
            ListNode listNode2 = new ListNode(2);
            ListNode listNode3 = new ListNode(3);
            ListNode listNode4 = new ListNode(4);
            ListNode listNode5 = new ListNode(5);
            head.next = listNode2;
            listNode2.next = listNode3;
            listNode3.next = listNode4;
            listNode4.next = listNode5;
            ListNode ansListNode = getReverse(head);
            while (ansListNode != null) {
                System.out.print(" " + ansListNode.value);
                ansListNode = ansListNode.next;
            }
        }
    }
    
  • 相关阅读:
    别人好的资源路径
    是否为微信浏览器,苹果安卓判断
    iframe滚动条置顶
    hadoop之MapReduce WordCount分析
    CentOS FTP服务器权限控制
    linux之sed用法
    hdfs-over-ftp安装与配置
    mysql grant all privileges on
    Notepad++快捷键大全
    coconHashMap实现原理分析
  • 原文地址:https://www.cnblogs.com/fyusac/p/14076704.html
Copyright © 2011-2022 走看看