package linkedlist;
class HeroNode {
public int no;
public String name;
public String nickName;
public HeroNode next;
public HeroNode(int no, String name, String nickName) {
super();
this.no = no;
this.name = name;
this.nickName = nickName;
}
@Override
public String toString() {
return "HeroNode [no=" + no + ", name=" + name + ", nickName=" + nickName + "]";
}
}
class SimpleLinkedList {
HeroNode head = new HeroNode(0, "", "");
public void addNode(HeroNode node) {
HeroNode temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = node;
}
public void showList() {
HeroNode temp = head.next;
while (true) {
if (temp == null) {
break;
}
System.out.println(temp);
temp = temp.next;
}
}
// 按编号顺序添加到链表中
public void addListByOrder(HeroNode node) {
HeroNode temp = head;
boolean flag = false;
while (true) {
if (temp.next == null) {
break;
}
if (temp.no > node.no) {
break;
} else if (temp.no == node.no) {
flag = true;
break;
} else {
temp = temp.next;
}
}
if (flag) {
System.out.println(node + "已经存在");
} else {
node.next = temp.next;
temp.next = node;
}
}
// 修改结点信息根据编号
public void updateNode(HeroNode node) {
if (head.next == null) {
System.out.println("链表为空");
return;
}
HeroNode temp = head.next;
boolean flag = true;
while (flag) {
if (temp == null) {
break;
}
if (temp.no == node.no) {
temp.name = node.name;
temp.nickName = node.nickName;
flag = false;
} else {
temp = temp.next;
}
}
if (flag) {
System.out.println("没有该节点");
} else {
System.out.println("修改成功");
}
}
// 根据no 删除节点
public void delete(HeroNode node) {
HeroNode temp2 = head.next;
HeroNode temp1 = head;
if (temp2 == null) {
System.out.println("链表为空");
return;
}
boolean flag = true;
while (flag) {
if (temp2 == null) {
break;
}
if (temp2.no == node.no) {
temp1.next = temp2.next;
flag = false;
} else {
temp1 = temp2;
temp2 = temp2.next;
}
}
if (flag) {
System.out.println("没有该节点");
} else {
System.out.println("修改成功");
}
}
}
public class SimpleLinkedListDemo {
public static void main(String[] args) {
HeroNode h1 = new HeroNode(1, "唐僧", "唐三藏");
HeroNode h2 = new HeroNode(2, "孙悟空", "齐天大圣");
HeroNode h5 = new HeroNode(6, "白龙马", "浪里小白龙");
HeroNode h3 = new HeroNode(3, "猪八戒", "天蓬元帅");
HeroNode h4 = new HeroNode(4, "沙僧", "沙和尚");
SimpleLinkedList linkedList = new SimpleLinkedList();
linkedList.addListByOrder(h1);
linkedList.addListByOrder(h2);
linkedList.addListByOrder(h3);
linkedList.addListByOrder(h4);
linkedList.showList();
linkedList.updateNode(h5);
linkedList.showList();
linkedList.delete(h5);
linkedList.showList();
}
}
Java 单链表相关操作
最新推荐文章于 2024-09-03 09:28:19 发布