尾插法链表java实现
创建节点
package list; public class HeroNode { private int no; private String name; private String nickname; private HeroNode next; public HeroNode() { super(); // TODO Auto-generated constructor stub } //构造器 public HeroNode(int no, String name, String nickname) { super(); this.no = no; this.name = name; this.nickname = nickname; } public int getNo() { return no; } public void setNo(int no) { this.no = no; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public HeroNode getNext() { return next; } public void setNext(HeroNode next) { this.next = next; } @Override public String toString() { return "HeroNode [no=" + no + ", name=" + name + ", nickname=" + nickname + "]"; } } *创建链表* ```java package list; public class HeroList {//尾插法 //初始化头结点,为了保证Head不被修改,这里就只设置了get方法 private HeroNode head = new HeroNode(0, null, null); public HeroNode getHead() { return head; } //添加节点到尾部 public void add(HeroNode hero) { //找到最后一个节点 HeroNode temp; temp = head; while(temp.getNext() != null) { //找到最后的节点 temp = temp.getNext(); } temp.setNext(hero); } //判断链表是否为空 public boolean isEmpty() { if(this.getHead().getNext() == null) { return true; } return false; } //修改节点 public void updateByNo(HeroNode newHero) { int no = newHero.getNo(); if(this.isEmpty()) { System.out.println("链表为空!"); return; } HeroNode temp = head.getNext(); while(temp != null) { if(temp.getNo() == no) { temp.setName(newHero.getName()); temp.setNickname(newHero.getNickname()); System.out.println("修改成功"); return; } temp = temp.getNext(); } System.out.println("未找到该节点"); } //删除节点 public void deleteByNo(int no) { if(this.isEmpty()) { System.out.println("链表为空!"); return; } HeroNode temp = head; while(temp.getNext() != null) { if(temp.getNext().getNo() == no) { temp.setNext(temp.getNext().getNext()); System.out.println("删除成功"); return; } temp = temp.getNext(); } System.out.println("未找到该节点"); } //显示节点 public void showHero() { HeroNode temp = this.head.getNext(); if(this.isEmpty()) { System.out.println("链表为空"); return; } while(temp != null) { System.out.println(temp); temp = temp.getNext(); } } }