package com.exercise.test; public class Main { public static void main(String[] args) { Link link = new Link(); link.add(1); link.delete(1); link.print(); System.out.println(link.getSize()); } } class Link{ private Node root; //链表头节点 private Node lastnNode; //链表尾节点 private int size; //链表长度 //链表的节点 class Node{ private int val; //节点值 private Node next; //节点的后驱 public Node(int x){ this.val = x; } public int getVal(){ return this.val; } } //链表中添加新节点,值为x,添加在尾部 public void add(int x){ Node node = new Node(x); if (this.root == null){ this.root = node; this.size = 1; this.lastnNode = this.root; }else { this.lastnNode.next = node; this.lastnNode = node; this.size++; } } //删除链表中值为x的节点 public int delete(int x){ if (this.root == null){ System.out.println("This link is null, please add node!"); return -1; }else { Node p = this.root; Node flag = new Node(-1); flag.next = p;
//查找链表中值为x的节点 while (p.val != x && p != null){ p = p.next; flag = flag.next; } if (p == null){ System.out.println("Can not find this node!"); return -1; } flag.next = p.next; //判断删除的节点是否为尾节点 if (p == this.lastnNode){ this.lastnNode = flag; } else { p.next = null; } //判断删除的节点是否为头节点 if (p == this.root){ this.root = flag.next; } this.size--; return x; } } //返回该链表节点数 public int getSize(){ return this.size; } //打印该链表 public void print(){ if (this.root != null){ System.out.print(this.root.getVal()); Node p = this.root.next; while (p != null){ System.out.print(" ---> " + p.getVal()); p = p.next; } System.out.println(); }else { System.out.println("This link is null"); } } }
上述创建的链表默认节点的元素类型为正整数且节点的值各不相同。代码仅简单的描述了Java如何创建一个简答的单链表,使用root和lastNode分别表示链表的头节点和尾节点。
维护lastNode是为了方便直接在链表的尾部添加新的节点而不必每次添加有需要遍历到链表的尾部节点再去添加,使得链表在尾部添加新节点的时间复杂度为O(1)。