• 反转单链表


    如何反转单链表。

    /**
     * @author miao
     *
     *         反转单链表
     */
    public class ResverList {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
    
            //
            ListNode head = genNode(4);
            printLink(head);
            ListNode revList = ReverseList(head);
            printLink(revList);
        }
        
        private static Random r = new Random();
        public static ListNode genNode(int m) {
            ListNode head = null;
            ListNode reHead = head;
            for(int i = 0;i<m;i++) {
                if(head == null) {
                    head = new ListNode(r.nextInt(m));
                    reHead = head;
                }else {
                    head.next = new ListNode(r.nextInt(m));;
                    head = head.next;
                }
            }
            return reHead;
        }
    
        public static ListNode ReverseList(ListNode head) {
            ListNode pre = null;
            ListNode next = null;
            while (head != null) {
                next = head.next; // 当前节点的下一个节点
                head.next = pre; //
                pre = head;
                head = next;
            }
            return pre;
        }
    
        public static void printLink(ListNode h) {
            System.out.println("begin");
            while (h != null) {
                System.out.print(" node -> " + h.val);
                h = h.next;
            }
            System.out.println();
            System.out.println("end");
        }
    
    }
    
    /**
     * 单链表
     * 
     * @author miao
     *
     */
    class ListNode {
        int val;
        ListNode next = null;
    
        public ListNode(int val) {
            this.val = val;
        }
    }

    核心逻辑为

        public static ListNode ReverseList(ListNode head) {
            ListNode pre = null;
            ListNode next = null;
            while (head != null) {
                next = head.next; // 当前节点的下一个节点
                head.next = pre; //
                pre = head;
                head = next;
            }
            return pre;
        }
  • 相关阅读:
    ionic2简单分析
    mvc的真实含义
    JavaSE学习总结(十七)—— IO流
    vs2010快捷键;sql server 2008快捷;IE9快捷键
    设计模式之六大设计原则
    通过peview分析PE文件
    游戏限制多开原理及对应方法
    inline hook原理和实现
    vm tools安装包为空
    Linux下PWN环境搭建
  • 原文地址:https://www.cnblogs.com/brave-rocker/p/13976278.html
Copyright © 2020-2023  润新知