package DataStructure;
/**
* Created with IntelliJ IDEA.
* Description:
* User: 86178
* Date: 2024-02-05
* Time: 21:25
*/
public class LinkedList {
public static void main(String[] args) {
HeroNode h1=new HeroNode(1,"宋江","及时雨");
HeroNode h2=new HeroNode(2,"卢俊义","玉麒麟");
HeroNode h3=new HeroNode(3,"吴用","智多星");
HeroNode h4=new HeroNode(4,"林冲","豹子头");
SingleList l=new SingleList();
l.addByOrder(h2);
l.addByOrder(h1);
l.addByOrder(h4);
l.addByOrder(h3);
//todo 提示编号3英雄已经存在 l.addByOrder(h3);
l.list();
System.out.println(getLength(l.getHead()));
}
//todo 获取单链表有效节点的个数(如果带头节点,去掉头节点)
public static int getLength(HeroNode head){
if(head.next==null){
//说明这是一个带头节点的空链表
return 0;
}
int cnt=0;
HeroNode cur=head.next;
while(cur!=null){
//todo 除了null节点之外的节点都是有效节点
cnt++;
cur=cur.next;
}
return cnt;
}
}
class SingleList{
//todo (HeroNode)单链表
//初始化头节点
private HeroNode head=new HeroNode(0,"","");
public HeroNode getHead(){
return head;
}
//添加节点
//todo 不考虑英雄的编号顺序
public void add(HeroNode h){
HeroNode cur=head;
//todo 改变链表结构需要遍历至null的前一个节点,从而添加元素
while(cur.next!=null){
cur=cur.next;
//找到链表末尾
}
cur.next=h;
}
//todo 按照排名添加英雄 如果排名存在则添加失败,进行提示
public void addByOrder(HeroNode h){
boolean flag=false;
HeroNode cur=head;
while(true){
if(cur.next==null){
//说明到达链表末尾
break;
}else if(cur.next.no>h.no){
break;
}else if(cur.next.no==h.no){
//说明节点已经存在
flag=true;
break;
}
cur=cur.next;
}
if(flag){
System.out.printf("无法添加,%d编号已经存在",h.no);
}else{
h.next=cur.next;
cur.next=h;
}
}
//todo 修改节点信息 no不能改
public void update(HeroNode newNode){
if(head.next==null){
System.out.println("链表为空");
return;
}
HeroNode cur=head.next;
boolean flag=false;
while(true){
if(cur==null){
//到了最后的null
break;
}else if(cur.no==newNode.no){
//说明找到了
flag=true;
break;
}
cur=cur.next;
}
if(flag){
//找到了待修改节点
cur.name=newNode.name;
cur.nickName=newNode.nickName;
}else{
System.out.printf("没有找到编号为%d的节点\n",newNode.no);
}
}
//todo 根据编号删除节点 编号不存在则进行提示
public void delete(int n){
if(head.next==null){
System.out.println("链表为空");
return;
}
boolean flag=false;
HeroNode cur=head;
//todo 指向head 因为需要是cur.next.no进行比较。如果直接指向第一个节点,则第一个节点无法进行比较
while(true){
if(cur.next==null){
//说明链表遍历完毕
break;
}
if(cur.next.no==n){
//说明找到了
flag=true;
break;
}
cur=cur.next;
}
if(flag){
//找到了
cur.next=cur.next.next;
}else{
System.out.printf("编号为%d的节点不存在\n",n);
}
}
public void list(){
if(head.next==null){
System.out.println("链表为空");
return;
}
//todo head不存放具体的数据,head指向链表的头节点
HeroNode cur=head.next;
while(cur!=null){
System.out.println(cur);
cur=cur.next;
}
System.out.print("null\n");
}
}
class HeroNode{
public int no;//编号
public String name;//名字
public String nickName;//昵称
public HeroNode next;
//指向下一个节点
//todo 构造器
public HeroNode(int no,String name,String nickName){
this.no=no;
this.name=name;
this.nickName=nickName;
}
//为了显示方便
@Override
public String toString(){
return "HeroNode[no="+no+",name="+name+",nickName="+nickName+"]";
}
}
尚硅谷Java数据结构--单链表(求链表中有效节点的个数)
最新推荐文章于 2024-09-26 18:42:37 发布