class SingleLinkedList{
//头节点,不可动
private final HeroNode head = new HeroNode(0,"","");
public void add(HeroNode heroNode){
HeroNode temp = head; //从头节点开始便利,临时保存数据
while (true){
if (temp.getNext() == null){ //最后一位
break;
}
temp = temp.getNext();
}
temp.setNext(heroNode);
}
//按顺序添加
public void addByOrder(HeroNode heroNode){
HeroNode temp = head; //从头节点开始便利,临时保存数据,获取是no>heroNode.no的前一位
while (true){
if (temp.getNext() == null){
break;
}
if (temp.getNext().getNo() > heroNode.getNo()){
break;
}else if (temp.getNext().getNo() == heroNode.getNo()){
System.out.println("元素已经存在");
}
temp = temp.getNext();
}
if (temp.getNext() != null) {
heroNode.setNext(temp.getNext());
}
temp.setNext(heroNode);
}
public void update(HeroNode heroNode){
HeroNode temp = head.getNext();
while (true){
if (temp == null){ //最后一位
break;
}
if (temp.getNo() == heroNode.getNo()){
temp.setName(heroNode.getName());
temp.setNickName(heroNode.getNickName());
break;
}
temp = temp.getNext();
}
}
public void delete(int no){
HeroNode temp = head; //指向被删除节点的前一个位置
while (true){
if (temp.getNext() == null){
break;
}
if (temp.getNext().getNo() == no){
temp.setNext(temp.getNext().getNext()); //被删除的前面一个节点链接它后面一个节点
break;
}
temp = temp.getNext();
}
}
public void list(){
if (head.getNext() == null){
System.out.println("列表为空");
return;
}
HeroNode temp = head.getNext();
while (true){
//判断是否是链表最后一行
if (temp == null){
break;
}
System.out.println(temp.toString());
temp = temp.getNext();
}
}
}
class HeroNode{
private int no;
private String name;
private String nickName;
private HeroNode next;
public HeroNode(int no, String name, String nickName) {
this.no = no;
this.name = name;
this.nickName = nickName;
}
public int getNo() {
return 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 + '\'' +
'}';
}
}
|