Article Directory
Operation of singly linked list
Node modification
-
On the basis of the list of previously created on the node where we make changes:
编号不变,英雄名称和昵称可以改变
. -
The main idea is to pass in a new node (the node number is arbitrary) through the modification method, and if the node number is equal to the existing node, modify it; otherwise, it is not easy to modify.
//进行节点的修改 ---- 根据no编号进行
public void update(HeroNode newHeroNode){
if (head.next==null){
System.out.println("链表为空!");
return;
}
// 构建辅助节点
HeroNode temp = head.next;
boolean flag = false; // 表示节点的编号是否存在
while (true){
if (temp==null){
break; // 链表遍历结束
}
// 节点编号存在
if (temp.no == newHeroNode.no){
flag = true;
break;
}
temp = temp.next;
}
// 根据flag判断是否修改
if (flag){
temp.name = newHeroNode.name;
temp.nickName = newHeroNode.nickName;
} else {
System.out.printf("没有找到编号为%d的英雄!",newHeroNode.no);
}
}
test
// 输出链表
singleLinkedList.showList();
// 修改节点
singleLinkedList.update(new HeroNode(5,"阿逵","小逵逵"));
// 输出链表
singleLinkedList.showList();
Deletion of nodes
The deletion of a node means that the next field in the middle of the linked list is continuously pointed to a break, so we need to reconnect the next field from the deleted node. As shown in the above figure, suppose we want to delete the data 4 node. Since the next field of data 4 points to data 7, and the next field of data 1 points to data 4, we now want the next field of data 1 to point to data 7.
The main idea:
- 1. The head node still can't move, the same is with the help of temp auxiliary node
- 2. When compared
temp.next.no
with the要被删除的节点的no
comparison.
// 删除节点
public void delete(int no){
// 创建辅助节点
HeroNode temp = head;
boolean flag = false; // 代表是否找到要删除的节点
while (true){
if (temp.next == null){
break;
}
if (temp.next.no == no){
flag = true;
break;
}
temp = temp.next;
}
// 判断是否找到
if (flag){
temp.next = temp.next.next;
} else {
System.out.printf("没有找到要删除编号为%d的节点\n",no);
}
}
// 删除节点
singleLinkedList.delete(5);
singleLinkedList.showList();
singleLinkedList.delete(5);
singleLinkedList.showList();
test