package com.example.sgg.data.linkedlist;
/**
* 双向链表
* Created by Administrator on 2021/7/14 0014.
* 与单向链表的区别
* 1、单向链表查找只能一个方向,而双向链表可以向前或向后查找
* 2、单向链表删除需要靠辅助节点(找到前一个节点),而双向链表可以自我删除
*/
public class DoubleLinkedList {
public static void main(String[] args) {
System.out.println("双向链表测试");
//创建节点
HeroNode2 hero1 = new HeroNode2(1, "宋江", "及时雨");
HeroNode2 hero2 = new HeroNode2(2, "卢俊义", "玉麒麟");
HeroNode2 hero3 = new HeroNode2(3, "吴用", "智多星");
HeroNode2 hero4 = new HeroNode2(4, "林冲", "豹子头");
//创建一个双向链表
DoubleLinkedList doubleLinkedList = new DoubleLinkedList();
doubleLinkedList.add(hero1);
doubleLinkedList.add(hero2);
doubleLinkedList.add(hero3);
doubleLinkedList.add(hero4);
//遍历展示
doubleLinkedList.list();
//修改
HeroNode2 newHero = new HeroNode2(4, "林冲冲", "豹子头");
doubleLinkedList.update(newHero);
System.out.println("修改后");
doubleLinkedList.list();
//删除
doubleLinkedList.delete(3);
System.out.println("删除后");
doubleLinkedList.list();
}
//先初始化一个头节点,头节点不要动,不存放具体的数据
private HeroNode2 head = new HeroNode2(0, "", "");
public HeroNode2 getHead() {
return head;
}
//显示链表[遍历]
public void list() {
if (head.next == null) {
System.out.println("链表为空");
}
HeroNode2 temp = head;
while (true) {
temp = temp.next;
System.out.println(temp.toString());
if (temp.next == null) {
break;
}
}
}
//添加一个节点到双向链表末尾
public void add(HeroNode2 heroNode) {
//因为head节点不能动,因此我们需要一个辅助变量temp
HeroNode2 temp = head;
//遍历链表找到最后一个节点
while (true) {
if (temp.next == null) {
break;
}
//如果没有找到,就讲temp后移
temp = temp.next;
}
temp.next = heroNode;
heroNode.pre = temp;
}
//TODO 课堂作业 按顺序添加节点
//根据编号来修改,编号不能修改,和单向链表一样
public void update(HeroNode2 heroNode) {
if (head.next == null) {
System.out.printf("链表为空");
}
HeroNode2 temp = head.next;
while (true) {
if (temp == null) {//遍历完了还找不到对应的编号
break;
}
if (temp.no == heroNode.no) {//找到对应编号的英雄节点
break;
}
temp = temp.next;
}
if (temp == null) {
System.out.printf("无对应编号%d的英雄,无法修改\n", heroNode.no);
return;
}
temp.name = heroNode.name;
temp.nickName = heroNode.nickName;
}
//删除节点
public void delete(int no) {
if (head.next == null) {
System.out.println("链表为空,无法删除");
}
HeroNode2 temp = head.next;
boolean flag = false;
while (true) {
if (temp == null) {
break;
}
if (temp.no == no) {
//找到该节点的前一个节点temp
flag = true;
break;
}
temp = temp.next;//移动到下一个节点
}
if (flag) {
temp.pre.next = temp.next;
if (temp.next !=null) {//必须加,防止最后一个删除最后一个节点
temp.next.pre = temp.pre;
}
} else {
System.out.printf("无对应编号%d的英雄,无法删除\n", no);
}
}
}
//定义一个HeroNode, 每个对象都是一个节点
class HeroNode2 {
public int no;
public String name;
public String nickName;
public HeroNode2 next;//指向下一个节点
public HeroNode2 pre;//指向前一个节点
public HeroNode2(int no, String name, String nickName) {
this.no = no;
this.name = name;
this.nickName = nickName;
}
//为了显示方便,重写toString
@Override
public String toString() {
return "HeroNode2{" +
"no=" + no +
", name='" + name + '\'' +
", nickName='" + nickName + '\'' +
'}';
}
}
|