数据结构之双项链表的操作
前面给出了单项链表的CRUD等操作,下面是对双向链表的一些操作
package com.ebiz.list; /** * @author YHj * @create 2019-07-17 16:48 */ public class DoubleListDemo { public static void main(String[] args) { //创建节点 HeroNode heroNode01 = new HeroNode(1, "宋江", "及时雨"); HeroNode heroNode02 = new HeroNode(2, "卢俊义", "玉麒麟"); HeroNode heroNode03 = new HeroNode(3, "无用", "智多星"); HeroNode heroNode04 = new HeroNode(4, "林冲", "豹子头"); //创建双向链表 DoubleList doubleList = new DoubleList(); //添加节点 doubleList.add(heroNode01); doubleList.add(heroNode02); doubleList.add(heroNode03); doubleList.add(heroNode04); //遍历节点 doubleList.list(doubleList); //修改节点 doubleList.update(new HeroNode(3,"有用","梦想")); System.out.println("修改节点之后遍历----------------------------------------------"); doubleList.list(doubleList); //删除节点 System.out.println("删除节点----------------------------------------------------"); doubleList.del(4); doubleList.list(doubleList); } } //链表类 class DoubleList{ //初始化头结点 private HeroNode head = new HeroNode(0, "", ""); // 遍历节点 public void list(DoubleList doubleList) { //判断是否为空 if (null == doubleList.head.next) { System.out.println("链表为空"); } //临时节点 HeroNode temp = head.next; while (true) { if (null == temp) { break; } System.out.println("temp = " + temp); temp = temp.next; } } //新增一个节点 public void add(HeroNode heroNode) { //临时节点 HeroNode temp = head; //找到最后一个节点 while (true) { if (temp.next == null) { break; } temp = temp.next; } //while循环退出,找到最后一个节点,添加新节点 temp.next = heroNode; heroNode.pre=temp; } //修改对应节点 public void update(HeroNode heroNode) { //临时节点 HeroNode temp = head; //boolean 判断链表中是否存在对应节点 boolean isExist = false; while (true) { if (null == temp) { break; } if (temp.no == heroNode.no) { isExist = true; break; } temp = temp.next; } if (isExist) { temp.name = heroNode.name; temp.nickname = heroNode.nickname; } else { System.out.println("没有对应英雄!!!"); } } //删除一个节点 public void del(int no){ if (null == head.next){ System.out.println("链表为空,无法删除!"); } //定义标识符 boolean isExist=false; //定义临时节点 HeroNode temp=head.next; while (true){ if (null == temp){ break; } if (temp.no == no){ isExist = true; break; } temp =temp.next; } if (isExist){ temp.pre.next = temp.next; //当前节点为最后一个节点的话 还执行这个回报空指针异常 if (null != temp.next){ temp.next.pre = temp.pre; } }else { System.out.println("没有该节点!"); } } } //节点类 class HeroNode { public int no;//英雄编号 public String name;//英雄的名字 public String nickname;//英雄的名称 public HeroNode next;//下一个英雄节点 public HeroNode pre;//上一个英雄节点 //构造器 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 + '\'' + '}'; } }