class Node{ public int val; public Node next; public Node(int val){ this.val=val; } } class LinkList{ private Node head; private Node tail; //链表对象增加节点 public void addNode(Node node){ if (this.head==null){ //链表初始化,第一个节点 this.head=node; this.tail=node; this.tail.next=null; } else //链表最后挂载节点 { this.tail.next=node; this.tail=node; } } //查询节点 public Node getNode(int val) { Node temp=this.head; while (temp!=null) { if (temp.val==val) { return temp; } temp=temp.next; } return null; } //修改节点的值 public void updateNode(int val,int value){ Node temp=this.head; while (temp!=null) { if (temp.val==val) { temp.val=value; } temp=temp.next; } } //删除节点 public Node deleteNode(int val){ Node temp=this.head; if (this.head.val==val) { this.head=this.head.next; return temp; } while (temp.next!=null) { if (temp.next.val==val)//直接判断的当前节点的下一个节点的值; //所以必须判断下一个节点不能为null,即只判断到倒数第二个节点即可 { Node delNode=temp.next; temp.next=temp.next.next; //当前节点直接连接下一个节点的下一个节点 从而实现删除,当前节点的下一个节点 return delNode; } temp=temp.next; } return null; } //打印所有节点的值 public void getAllNodes(){ Node temp=this.head; while (temp!=null) { System.out.print(temp.val+" "); temp=temp.next; } System.out.println(); } } public class TestLink { public static void main(String[] args){ LinkList ll=new LinkList(); ll.addNode(new Node(1)); ll.addNode(new Node(2)); ll.addNode(new Node(3)); ll.addNode(new Node(4)); if (ll.getNode(3)!=null) { System.out.println(ll.getNode(3).val); } if (ll.getNode(5)!=null) { System.out.println(ll.getNode(5).val); } ll.updateNode(1,100); ll.updateNode(4,400); ll.updateNode(2,200); ll.updateNode(5,500); ll.addNode(new Node(5)); ll.addNode(new Node(6)); System.out.println("************"); ll.deleteNode(6); ll.getAllNodes(); ll.deleteNode(3); ll.deleteNode(1); ll.deleteNode(100); System.out.println("************"); ll.getAllNodes(); } }