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

    public class Test {
        class Node {
            Node next;
            int data;
    
            protected Node(int data) {
                this.data = data;
            }
        }
    
        /**
         * 构建单链表
         * 
         * @param nums
         * @return
         */
        private Node create(int[] nums) {
            if (nums.length == 0) {
                return null;
            }
            Node head = new Node(nums[0]), cur = head;
            for (int i = 1; i < nums.length; i++) {
                Node node = new Node(nums[i]);
                cur.next = node;
                cur = node;
            }
            return head;
        }
    
        /**
         * 链表反转
         * 
         * @param head
         * @return
         */
        private Node reverse(Node head) {
            Node newHead = null, tem;
            while (head != null) {
                tem = head;
                head = head.next;
                tem.next = newHead;
                newHead = tem;
            }
            return newHead;
        }
    
        /**
         * 打印单链表
         * 
         * @param head
         */
        private void print(Node head) {
            Node tem = head;
            while (tem != null) {
                System.out.print(tem.data + "->");
                tem = tem.next;
            }
            System.out.println("NULL");
        }
    
        private void test() {
            int[] nums = new int[] { 3, 1, 0, 9, 8, 11 };
            Node root = create(nums);
            print(root);
            Node fan = reverse(root);
            print(fan);
        }
    
        public static void main(String[] args) {
            new Test().test();
        }
    }

    结果输出:

    3->1->0->9->8->11->NULL
    11->8->9->0->1->3->NULL
  • 相关阅读:
    隔行扫描 和 逐行扫描
    CSS3--关于z-index不生效问题
    vue与其他框架对比
    跨域(转)
    vue 事件修饰符(阻止默认行为和事件冒泡)
    vue 3.0新特性
    bash leetcode
    数据库
    css排版
    盒模型
  • 原文地址:https://www.cnblogs.com/zhi-leaf/p/12819599.html
Copyright © 2011-2022 走看看