上文讲到了链表基础构造以及链表的insertFirst和deleteFirst方法,但是这两个方法只能查询到链头和删除链头,而不能针对链表中的某个节点进行操作,所以本文主要讲解操作链表LinkList的其他两个重要的方法:find方法和delete方法。
一 、链节点的查找
find方法,是通过传入一个数据key,通过这个数据来比对当前current节点(首先默认为first节点)的数据是否符合,如果数据符合,即找到该节点;反之,就是不符合,那么需要把current指向下一个结点,在去进行比对操作;当current.next是空节点时,停止循环停止。
//查找链表中的结点
public Link find(int key){
Link current = this.first;//将当前指向first结点
while(current.next != null){
//链表不为空时
if(current.data != key ){
//不是该数据,将current向下移动
current = current.next;
}else if(current.data == key){
System.out.println("已经找到该结点");
return current;
}
}
System.out.println("没有找到该节点");
return null;//没有找到链结点
}
二、链节点的删除
链节点的删除和链节点的查找相似,首先都是确定一个current变量去标记当前的节点,然后通过数据的对比去确认是不是该节点;但是链节点是删除有不同之处,就是不仅要知道current和current.next节点,还要知道current.pre节点,即当前节点的前节点。因为进行节点的删除操作,本质上就是将current的前节点和后节点相连接,current节点由Java GC机制回收,如图:
//链结点的删除
public void delete(int key){
Link current = this.first;
Link pre = null;
while(current.next != null){
if(current.data == key && current == this.first){
//要删除的是链头
this.first = current.next;
}else if(current.data != key){
pre = current;//将当前链结点赋值为链前结点
current = current.next;
}else if(current.data == key){
//找到要删除的current
pre.next = current.next;//删除,连接两个链结点 pre.next->current.next
System.out.println("已删除含"+key+"的链结点");
return;
}
}
System.out.println("找不到链结点");
}
三、测试
@Test
public void fun1(){
LinkList linkList = new LinkList();
linkList.insertFirst(1);
linkList.insertFirst(2);
linkList.insertFirst(3);
linkList.insertFirst(4);
linkList.insertFirst(5);
System.out.println("遍历1");
linkList.displayLinkList();
System.out.println("删除两个链头");
linkList.deleteFirst();
linkList.deleteFirst();
System.out.println("遍历2");
linkList.displayLinkList();
LinkList.Link link = linkList.find(4);
System.out.println(link);
linkList.delete(2);
linkList.displayLinkList();
}
}