zoukankan      html  css  js  c++  java
  • 反转单链表

    如何反转单链表。

    /**
     * @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;
        }
  • 相关阅读:
    Project Chameleon Work In Progress 14
    All about Project Chameleon
    网页中图片连续滚动代码 (转)
    一点感言
    一些常用javascript代码(转)
    asp.net(c#)的一个非常非常奇怪的问题
    用javascript拦截a标签的超链接执行
    asp.net中用TreeView控件实现无限分级的好办法
    windows7 安装ez usb基本驱动
    管道编程
  • 原文地址:https://www.cnblogs.com/brave-rocker/p/13976278.html
Copyright © 2011-2022 走看看