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
  • 相关阅读:
    leetcode : 3 sum
    leetcode : Merge two sorted lists
    算法:海量数据问题
    计算机基础:数据库
    计算机基础:Linux
    Java:JVM
    Java:Basic/集合框架/多线程
    Java:面试题
    框架:SSM整合
    LeetCode: Tags-[Bit Manipulation]
  • 原文地址:https://www.cnblogs.com/zhi-leaf/p/12819599.html
Copyright © 2011-2022 走看看