• 反转单链表


    如何反转单链表。

    /**
     * @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;
        }
  • 相关阅读:
    Python练习题
    python自动化学习笔记(六)
    Python自动化学习笔记( 五)
    自动化学习笔记之接口测试(一)
    python自动化学习笔记(四)
    vim编辑器命令
    linux之shell通配符
    Python自动化学习笔记(二)
    python自动化学习笔记(三)
    python学习笔记之常用操作符
  • 原文地址:https://www.cnblogs.com/brave-rocker/p/13976278.html
Copyright © 2020-2023  润新知