单链表之CRUD操作
Posted 程序彤
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了单链表之CRUD操作相关的知识,希望对你有一定的参考价值。
package 链表.单链表crud;
public class SingleLinkedListDemo {
public static void main(String[] args) {
SingleLinkedList sll = new SingleLinkedList();
HeroNode heroNode1 = new HeroNode(1, "虚空掠夺者");
HeroNode heroNode2 = new HeroNode(2, "风暴之怒");
HeroNode heroNode3 = new HeroNode(3, "盖伦");
HeroNode heroNode4 = new HeroNode(4, "寒冰");
sll.add(heroNode2);
sll.add(heroNode3);
sll.add(heroNode1);
sll.add(heroNode4);
sll.update(new HeroNode(3,"德玛西亚"));
sll.del(4);
sll.query();
}
}
class HeroNode {
public int id;
public String name;
public HeroNode next;
public HeroNode(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "HeroNode{" +
"id=" + id +
", name='" + name + '\\'' +
'}';
}
}
class SingleLinkedList {
public HeroNode head = new HeroNode(0, "");
// 增
public void add(HeroNode heroNode) {
HeroNode curr = head;
boolean isRepeated = false;
while (true) {
if (curr.next == null) { // 在末尾也可以去加
break;
}
if (curr.next.id > heroNode.id) { // 找到则退出循环去加
break;
}
if (curr.next.id == heroNode.id) {
isRepeated = true;
break;
}
curr = curr.next;
}
// 为了防止添加重复节点,这里做判断
if (isRepeated) {
System.out.printf("英雄编号%d已重复,不可重复添加~", heroNode.id);
}
heroNode.next = curr.next; // 这样写
curr.next = heroNode;
// curr.next = heroNode; // 这样写 则改变了当前节点的下一个节点
// heroNode.next = curr.next;
}
// 删
public void del(int id) {
HeroNode curr = head;
boolean isExist = true;
while (true) {
if (curr.next == null) { // 特殊情况处理
isExist = false;
break;
}
if (curr.next.id == id) { // 满足情况退出
break;
}
curr = curr.next;
}
if (!isExist) {
System.out.printf("英雄编号%d不存在,没有可以删除的~", id);
}
curr.next = curr.next.next;
}
// 改
public void update(HeroNode heroNode) {
HeroNode curr = head;
boolean isExist = true;
while (true) {
if (curr.next == null) { // 特殊情况处理
isExist = false;
break;
}
if (curr.next.id == heroNode.id) { // 满足情况退出
break;
}
curr = curr.next;
}
if (!isExist) {
System.out.printf("英雄编号%d不存在,没有可以修改的",heroNode.id);
}
curr.next.name = heroNode.name;
}
// 查
public void query(){
if (head.next == null) {
return;
}
HeroNode curr = head.next;
while (true) {
if (curr == null) { // 到链表最后一个的下一个即为null
break;
}
System.out.println(curr);
curr = curr.next;
}
}
}
以上是关于单链表之CRUD操作的主要内容,如果未能解决你的问题,请参考以下文章