双向链表(增删改查)
双向链表(增删改查)
准备结点类
结点类应该包含 前驱、后驱、DATA域
class HeroNode2 {
public int no;
public String name;
public String nickName;
public HeroNode2 next; //指向下一个结点
public HeroNode2 pre; //指向前一个结点
}
准备链表类
class DoubleLinkedList{
private HeroNode2 head = new HeroNode2(0,"","");
private HeroNode2 tail = head;
public HeroNode2 getHead() {
return head;
}
}
add()
public void add(HeroNode2 heroNode) {
tail.next = heroNode;
heroNode.pre = tail;
tail = heroNode;
}
addByOrder()
根据结点序号,按顺序添加
public void addByOrder(HeroNode2 heroNode) {
//链表为空,直接加入head后面
if(head.next==null){
head.next = heroNode;
heroNode.pre = head;
return;
}
HeroNode2 temp = head.next; //temp指向要比较的结点
boolean flag = false; //标志添加的编号是否存在,默认false
//寻找添加位置
while (temp!=null) {
if (temp.no > heroNode.no) {//当前结点no大于插入的no,前一个结点no小于插入的no
break;
} else if (temp.no == heroNode.no) {//说明希望添加的heroNode的编号已经存在
flag = true;
}
if(temp.next==null){
//判断是否是链表的尾部,是就保存最后一个结点
tail = temp;
}
temp = temp.next;//后移
}
//判断flag的值
if (flag) {//编号存在,不能添加
System.out.printf("准备插入的英雄编号%d 已经存在了,不能加入\n", heroNode.no);
} else {//编号不存在,插入到链表中,temp指针后面
if(temp==null){
//要插入的结点比链表中所有结点都大,temp就移动到了null
tail.next = heroNode;
heroNode.pre = tail;
}else{//在链表中间插入
heroNode.pre = temp.pre;
heroNode.next = temp;
temp.pre.next = heroNode;
temp.pre = heroNode;
}
}
}
update()
public void update(HeroNode2 newHeroNode) {
//判断链表是否为空
if (head.next == null) {
System.out.println("链表为空!");
return;
}
//找到需要修改的结点,根据no编号
//定义遍历指针
HeroNode2 temp = head;
while (temp != null && temp.no != newHeroNode.no) {
temp = temp.next;
}
if (temp == null) {
System.out.printf("没有找到编号 %d 的结点,不能修改\n", newHeroNode.no);
} else {
temp.name = newHeroNode.name;
temp.nickName = newHeroNode.nickName;
}
}
del()
public void del(int no) {
//判断链表是否为空
if (head.next == null) {
System.out.println("链表为空!");
return;
}
//定义指针
HeroNode2 temp = head.next;
while (temp != null && temp.no != no) {
temp = temp.next;
}
if (temp == null) {//没有找到删除结点,temp就移动到了链尾
System.out.printf("没有找到编号 %d 的结点,不能删除\n", no);
} else {//找到删除结点,temp指向链表中间
temp.pre.next = temp.next;
if(temp.next != null) {
temp.next.pre = temp.pre;
}
}
}
打印链表
public void list() {
//先判断链表是否为空
if (head.next == null) {
System.out.println("链表为空");
return;
}
HeroNode2 temp = head.next;
while (temp != null) {
//输出结点信息
System.out.println(temp);
//将temp后移
temp = temp.next;
}
}