首页 > 编程知识 正文

单链表代码实现

时间:2023-05-06 10:13:31 阅读:222236 作者:4199

单链表 从链表头插入信息 //从链表头插入信息 public void addFirst(HeroNode hero){ HeroNode newhero=hero; if (isEmpty()){ last=newhero; } newhero.next=first; first=newhero; } 从链表尾插入信息 //从链表尾插入信息 public void addLast(HeroNode hero){ HeroNode newhero=hero; if (isEmpty()){ first=newhero; }else { last.next = newhero; } last=newhero; } 删除指定位置上的数据 //删除指定位置上的数据 public boolean delete(int rank){ if (isEmpty()){ return false; } else { HeroNode current = first; HeroNode previous = first; while (current.rank!=rank){ if (current.next==null){ return false; } else{ previous=current; current=current.next; } } if (current==first){ first=current.next; } else{ previous.next=current.next; } return true; } } 显示列表 //显示列表public void show(){ if (isEmpty()){ System.out.println("链表为空"); return; } HeroNode temp =first; while (true){ if (temp==null){ break; } else{ System.out.println(temp); temp= temp.next; } }}

完整代码 :

package list;/** * @author ren * @date 2020/8/5-17:31 * @describe */public class SingleList2 { public int size; private HeroNode first; private HeroNode last; public SingleList2(){ first=null; last=null; } public static class HeroNode{ public int rank; public String name; public String sword; public HeroNode next; public HeroNode(int rank, String name, String sword) { this.rank = rank; this.name = name; this.sword = sword; } @Override public String toString() { return "HeroNode{" + "rank=" + rank + ", name='" + name + ''' + ", sword='" + sword + ''' + '}'; } } //判断链表是否为空 public boolean isEmpty(){ return first==null; } //添加信息 //从链表头插入信息 public void addFirst(HeroNode hero){// HeroNode newhero=new HeroNode(hero); HeroNode newhero=hero; if (isEmpty()){ last=newhero; } newhero.next=first; first=newhero; } //从链表尾插入信息 public void addLast(HeroNode hero){// HeroNode newhero=new HeroNode(hero); HeroNode newhero=hero; if (isEmpty()){ first=newhero; }else { last.next = newhero; } last=newhero; } //删除指定位置上的数据 public boolean delete(int rank){ if (isEmpty()){ return false; } else { HeroNode current = first; HeroNode previous = first; while (current.rank!=rank){ if (current.next==null){ return false; } else{ previous=current; current=current.next; } } if (current==first){ first=current.next; } else{ previous.next=current.next; } return true; } } //显示列表 public void show(){ if (isEmpty()){ System.out.println("链表为空"); return; } HeroNode temp =first; while (true){ if (temp==null){ break; } else{ System.out.println(temp); temp= temp.next; } } } public static void main(String[] args) { HeroNode hero1=new HeroNode(1,"嬴政","天问"); HeroNode hero2=new HeroNode(2,"asjdm","渊虹"); HeroNode hero3=new HeroNode(3,"平常的手链","太阿"); SingleList2 singleList2 = new SingleList2(); singleList2.addLast(hero1); singleList2.addLast(hero2); singleList2.addLast(hero3); singleList2.show(); System.out.println("------------------------"); singleList2.delete(3); singleList2.show(); } }

测试结果:

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。