• Java 创建链表,增删改查


    项目结构:

    Node.java:

    package linkedList;
    
    public class Node {
        int data;
        Node next;
    
        public Node(int data) {
            this.data = data;
            this.next = null;
        }
    }
    View Code

    LinkedList.java:

    package linkedList;
    
    public class LinkedList {
        private Node first; //指向第一个节点(默认为null)
        private Node last;  //指向第二个节点
    
        //判断链表是否为空
        public boolean isEmpty(){
            return (first==null);
        }
    
        //打印链表元素
        public void print(){
            Node current = first;   //定义游标指向头节点
            while (current != null){
                System.out.print(current.data + "   ");
                current = current.next;
            }
            System.out.println();
        }
    
        public void insert(int data){
            Node newNode = new Node(data); //封装数据
            if(this.isEmpty()){     //若当前是空链表
                first = newNode;    //头和尾都指向该节点
                last = newNode;
            }else{      //该链表非空
                last.next = newNode;
                last = newNode;
            }
        }
    
        public static void test(){
            LinkedList linkedList = new LinkedList();
    
            System.out.println("输入5个数据:");
            linkedList.insert(10);
            linkedList.insert(20);
            linkedList.insert(30);
            linkedList.insert(40);
            linkedList.insert(50);
    
            System.out.println("打印链表:");
            linkedList.print();
        }
    }
    View Code

    Test.java:

    import linkedList.LinkedList;
    
    public class Test {
        public static void main(String[] args) {
            LinkedList.test();
        }
    }
    View Code

    结果:

    创建、添加元素:

  • 相关阅读:
    Es module vs require
    phaser3 画虚线实现
    新的计划
    [转]Boostrap Table的refresh和refreshOptions区别
    Storing Java objects in MySQL blobs
    【转】Ubuntu下搜狗输入法突然无法输入中文
    团队作业六
    团队作业七
    团队作业四
    团队作业三
  • 原文地址:https://www.cnblogs.com/CPU-Easy/p/12403412.html
Copyright © 2020-2023  润新知