项目结构:
Node.java:
package linkedList; public class Node { int data; Node next; public Node(int data) { this.data = data; this.next = null; } }
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(); } }
Test.java:
import linkedList.LinkedList; public class Test { public static void main(String[] args) { LinkedList.test(); } }
结果:
创建、添加元素: