package datastructure.linkedlist; public class LinkedListDemo { public static void main(String[] args) { LinkedList list = new LinkedList(); // list.add(new HeroNode(1, "AAA", "AAA")); // list.add(new HeroNode(5, "BBB", "BBB")); // list.add(new HeroNode(2, "CCC", "CCC")); list.addByOrder(new HeroNode(1, "AAA", "AAA")); list.addByOrder(new HeroNode(5, "BBB", "BBB")); list.addByOrder(new HeroNode(2, "CCC", "CCC")); list.list(); list.update(new HeroNode(2, "haha疼", "haha")); list.list(); System.out.println("-------------------"); list.delete(5); list.list(); } } class LinkedList { // 定义头结点 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; } // 根据no删除 public void delete(Integer no) { HeroNode temp = head; if (head.next == null) { System.out.println("链表为空"); return; } while (true) { if (temp.next == null) { System.out.println("不存在此编号"); break; } if (no == temp.next.no) { temp.next = temp.next.next; break; } temp = temp.next; } } // 根据编号修改 no不能变 public void update(HeroNode heroNode) { if (head.next == null) { System.out.println("链表为空"); return; } HeroNode temp = head; boolean flag = false; while (true) { if (temp.next == null) { break; } if (temp.no == heroNode.no) { flag = true; } if (flag == true) { temp.name = heroNode.name; temp.nickname = heroNode.nickname; } else { System.out.println("没有找到"); } temp = temp.next; } } public void addByOrder(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) { System.out.println("编号存在:" + heroNode.no); } heroNode.next = temp.next; temp.next = heroNode; } public void list() { if (head.next == null) { System.out.println("链表为空"); return; } HeroNode temp = head.next; while (true) { if (temp == null) { break; } System.out.println(temp); temp = temp.next; } } } class HeroNode { public Integer no; public String name; public String nickname; public HeroNode next; public HeroNode(Integer 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 + "]"; } }