标签:tostring == over href tde list display boolean out
1、链表的介绍
2、单链表的实例应用
包括节点的插入、修改和删除(很简单,我就不具体写步骤了,直接上代码!)
public class SingleLinkedListDemo { public static void main(String[] args) { HeroNode node1 = new HeroNode(1, "宋江", "及时雨"); HeroNode node2 = new HeroNode(2, "卢俊义", "玉麒麟"); HeroNode node3 = new HeroNode(3, "吴用", "智多星"); HeroNode node4 = new HeroNode(4, "林冲", "豹子头"); SingleLinkedList list = new SingleLinkedList(); list.addByOrder(node1); list.addByOrder(node4); list.addByOrder(node3); list.addByOrder(node2); list.list(); //修改节点 System.out.println("================================="); HeroNode newNode = new HeroNode(2, "庐州太太", "玉麒麟~~"); list.update(newNode); list.list(); //删除节点 System.out.println("================================="); list.delete(node1); list.delete(node2); list.list(); } } //定义一个LinkedList 来管理我们的英雄 class SingleLinkedList{ //定义一个头节点,不存对象 private HeroNode head = new HeroNode(0,"",""); //添加节点到链表 // 第一种添加英雄的方式,直接在链表尾部添加 public void add(HeroNode hero){ HeroNode temp = head; while(true){ if(temp.next==null){ break; } temp=temp.next; } temp.next=hero; } // 第二种添加英雄的方式,根据排名将英雄插入到指定的位置 public void addByOrder(HeroNode hero){ HeroNode temp = head; boolean flag = false; //标志和添加的节点和链表中节点的编号没有重复 while(true){ if(temp.next==null){ break; } if(temp.next.no>hero.no){ break; }else if(temp.next.no == hero.no){ flag = true; break; } temp=temp.next; } if(flag){ System.out.println("链表中已存在要添加的节点!"); }else{ hero.next = temp.next; temp.next = hero; } } //单链表的修改 public void update(HeroNode hero){ if(head.next==null){ System.out.println("链表为空!!"); } HeroNode temp = head; boolean flag = false; //标志是否在链表中找到 no==hero.no 的节点 while(true){ if(temp.next==null){ break; } if(temp.next.no==hero.no){ flag=true; break; } temp=temp.next; } if(flag){ temp.next.name =hero.name; temp.next.nickName =hero.nickName; }else{ System.out.printf("未在链表中找到no为%d的节点",hero.no); } } //节点的删除 public void delete(HeroNode hero){ if(head.next==null){ System.out.println("链表为空!!"); } HeroNode temp = head; boolean flag = false; //标志是否在链表中找到待删除节点 while(true){ if(temp.next==null){ break; } if(temp.next.no==hero.no){ flag=true; break; } temp=temp.next; } if(flag){ temp.next=temp.next.next; //删除节点 }else{ System.out.printf("no为%d的节点不存在",hero.no); } } //显示链表【遍历】 public void list(){ if(head.next==null){ System.out.println("链表为空!"); return; } HeroNode temp = head; while(true){ if(temp.next==null){ break; } temp=temp.next; System.out.println(temp); } } } //定义一个HeroNode,每个 HeroNode 就是一个节点 class HeroNode{ public int no; public String name; public String nickName; public HeroNode next; //构造器 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 + ‘\‘‘+‘}‘ ; } }
标签:tostring == over href tde list display boolean out
原文地址:https://www.cnblogs.com/houchen/p/13384587.html