classNode{public intval;publicNode next;public Node(intval){this.val=val;
}
}classLinkList{privateNode head;privateNode tail;//链表对象增加节点
public voidaddNode(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(intval)
{
Node temp=this.head;while (temp!=null)
{if (temp.val==val)
{returntemp;
}
temp=temp.next;
}return null;
}//修改节点的值
public void updateNode(int val,intvalue){
Node temp=this.head;while (temp!=null)
{if (temp.val==val)
{
temp.val=value;
}
temp=temp.next;
}
}//删除节点
public Node deleteNode(intval){
Node temp=this.head;if (this.head.val==val)
{this.head=this.head.next;returntemp;
}while (temp.next!=null)
{if (temp.next.val==val)//直接判断的当前节点的下一个节点的值;//所以必须判断下一个节点不能为null,即只判断到倒数第二个节点即可
{
Node delNode=temp.next;
temp.next=temp.next.next; //当前节点直接连接下一个节点的下一个节点 从而实现删除,当前节点的下一个节点
returndelNode;
}
temp=temp.next;
}return null;
}//打印所有节点的值
public voidgetAllNodes(){
Node temp=this.head;while (temp!=null)
{
System.out.print(temp.val+" ");
temp=temp.next;
}
System.out.println();
}
}public classTestLink
{public static voidmain(String[] args){
LinkList ll=newLinkList();
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();
}
}