单链表的增删改查
package linkedList;
public class SingleLinkedListdemo {
public static void main(String[] args) {
SingleLinkedList singleLinkedList = new SingleLinkedList();
singleLinkedList.addByNo(new HeroNode(4, "dd", "ddd"));
singleLinkedList.addByNo(new HeroNode(1, "aa", "aaa"));
singleLinkedList.addByNo(new HeroNode(3, "cc", "ccc"));
singleLinkedList.addByNo(new HeroNode(2, "bb", "bbb"));
singleLinkedList.updateByNo(new HeroNode(3, "cc", "cccupdate"));
singleLinkedList.show();
System.out.println("*******************************");
singleLinkedList.delete(3);
singleLinkedList.show();
}
}
class SingleLinkedList {
private HeroNode head = new HeroNode(0, "", "");
public void add(HeroNode heroNode) {
HeroNode temp = head;
while (true) {
if (temp.next == null) {
break;
}
temp = temp.next;
}
temp.next = heroNode;
}
public void addByNo(HeroNode heroNode) {
HeroNode temp = head;
boolean flag = false;
while (true) {
if (temp.next == null) {
break;
}
if (temp.next.no > heroNode.no) {
break;
}
if (temp.next.no == heroNode.no) {
flag = true;
}
temp = temp.next;
}
if (flag == true) {
System.out.println("准备插入的数据的编号:" + heroNode.no + "已经存在");
return;
}
heroNode.next = temp.next;
temp.next = heroNode;
}
public void updateByNo(HeroNode heroNode) {
if (head.next == null) {
System.out.println("链表为空");
return;
}
HeroNode temp = head.next;
boolean isFind = false;
while (true) {
if (temp == null) {
break;
}
if (temp.no == heroNode.no) {
isFind = true;
break;
}
temp = temp.next;
}
if (isFind) {
temp.no = heroNode.no;
temp.name = heroNode.name;
temp.nickname = heroNode.nickname;
} else {
System.out.println("没有找到该编号的节点");
}
}
public void delete(int no) {
if (head.next == null) {
System.out.println("该链表为空");
}
HeroNode temp = head;
boolean isFind = false;
while (true) {
if (temp.next == null) {
System.out.println("未找到指定节点");
break;
}
if (temp.next.no == no) {
isFind = true;
break;
}
temp = temp.next;
}
if (isFind) {
temp.next = temp.next.next;
} else {
System.out.println("未找到指定节点");
}
}
public void show() {
if (head.next == null) {
System.out.println("链表为空");
}
HeroNode temp = head.next;
while (temp != null) {
System.out.println(temp);
temp = temp.next;
}
}
}
class HeroNode {
public int no;
public String name;
public String nickname;
public HeroNode next;
public HeroNode(int no, String name, String nickname) {
this.no = no;
this.name = name;
this.nickname = nickname;
}
@Override
public String toString() {
return "HeroNode{" +
"no=" + no +
", name='" + name + '\'' +
", nickname='" + nickname + '\'' + "}";
}
}