单链表的操作的综合例子--增删改查
单链表的增删改查的综合例子
需求描述:实现对水浒英雄榜的增删改查。进阶:按照顺序增加水浒英雄,并且支持反转。
第一步:首先定义一个HeroNode节点。代码如下所示:
public class HeroNode { public String heroName; public String nickName; public int heroNo; public HeroNode next; public HeroNode(String heroName,String nickName,int heroNo){ this.heroName=heroName; this.nickName=nickName; this.heroNo=heroNo; } @Override public String toString() { final StringBuilder sb = new StringBuilder("HeroNode{"); sb.append("heroName='").append(heroName).append('\''); sb.append(", nickName='").append(nickName).append('\''); sb.append(", heroNo=").append(heroNo); sb.append('}'); return sb.toString(); } }
接下来便来实现,最基本的增删改查
public class HeroSingleLinkedList { private HeroNode headNode=new HeroNode("","",0); public void add(HeroNode node){ if(headNode.next==null){ headNode.next=node; return; } HeroNode temp=headNode.next; while (true){ if(temp.next==null){ break; } temp=temp.next; } temp.next=node; } public void loopUp(){ if(headNode.next==null){ System.out.println("链表为空"); return; } HeroNode temp=headNode.next; while (true){ System.out.println(temp); if(temp.next==null){ break; } temp=temp.next; } } public void modify(HeroNode node){ if(headNode.next==null){ System.out.println("链表为空"); return; } HeroNode temp=headNode.next; while (true){ if(temp.next.heroNo==node.heroNo){ temp.next.nickName=node.nickName; temp.next.heroName=node.heroName; break; } temp=temp.next; } } public void delete(HeroNode node){ if(headNode.next==null){ System.out.println("链表为空"); return; } HeroNode temp=headNode.next; while (true){ if(temp.next.heroNo==node.heroNo){ break; } temp=temp.next; } temp.next=temp.next.next; } }
终极目标:世界大同