单向链表的缺点分析:
-
单向链表查找方向只能是一个方向,而双向链表可以向前或着向后查询
-
单链表不能自我阐述,需要靠辅助节点,而双向链表,可以自我删除
分析双向链表遍历,添加,修改,删除的操作思路:
-
遍历双和单链表一样,只是可以向前,也可以向后遍历
-
添加(默认添加到双向链表末尾)
-
先找到双向链表的最后这个点
-
temp.next = newHeroList
-
newHeroList.pre = temp
-
-
修改思路和原理同单链表一样
-
删除
-
因为时双线链表,可以实现链表的自我删除
-
直接找到这个要删除的节点,例如:temp
-
temp.pre.next = temp.next
-
temp.next.pre = temp.pre;
-
package com.number_solution2;
public class DoubleListDemo01 {
public static void main(String[] args) {
HeroList1 hero1 = new HeroList1(1,"松江","及时雨");
HeroList1 hero2 = new HeroList1(2,"灵宠","豹子头");
HeroList1 hero3 = new HeroList1(3,"李逵","黑旋风");
HeroList1 hero4 = new HeroList1(4,"吴用","智多星");
DoubleListDemo dou = new DoubleListDemo();
//添加数据
dou.add_list(hero1);
dou.add_list(hero2);
dou.add_list(hero3);
dou.add_list(hero4);
//展示
dou.show_list();
System.out.println("--------------");
System.out.println(hero3.pre);
//删除
dou.delete_list(1);
dou.show_list();
System.out.println("--------------");
System.out.println(hero3.pre);
}
}
class DoubleListDemo {
//创建头节点
HeroList1 heo = new HeroList1(0,"","");
//添加链表数据
public void add_list(HeroList1 list){
HeroList1 temp = heo;
while (true){
//找到链表最后
if(temp.next == null){
break;
}
//如果没有找到最后,将temp向后移
temp = temp.next;
}
//当退出循环时,temp就指向链表最后
temp.next = list;
list.pre = temp;
}
//修改节点的信息
public void change_list(HeroList1 list){
ifnull();
HeroList1 temp = heo.next;
while (true){
if (temp == null){
System.out.println("没有找到该链表");
break;
}
if(temp.no == list.no){
temp.name = list.name;
temp.nicename = list.nicename;
break;
}
temp = temp.next;
}
}
// 删除链表
public void delete_list(int no) {
// 判断链表是否为空
ifnull();
HeroList1 temp = heo;
// 循环遍历出链表
while (true) {
if (temp.next == null) {
System.out.println("没有找到该链表");
break;
}
// temp.next 为该链表
if (temp.next.no == no) {
HeroList1 toDelete = temp.next;
temp.next = toDelete.next;
if (toDelete.next!= null) {
toDelete.next.pre = temp;
}
System.out.println("已删除~~~");
break;
}
temp = temp.next;
}
}
//打印链表
public void show_list() {
//判断链表是否为空
ifnull();
HeroList1 temp = heo.next;
//结束遍历操作
while (true) {
if (temp == null){
break;
}
//输出节点信息
System.out.println(temp);
temp = temp.next;
}
}
public void ifnull(){
//判断链表是否为空
if (heo.next == null) {
System.out.println("链表为空~~");
return;
}
}
}
class HeroList1 {
public int no;
public String name;
public String nicename;
public HeroList1 next; //指向下一个节点
public HeroList1 pre; //指向前一个节点的
//构造器
public HeroList1(int no, String name, String nicename) {
this.no = no;
this.name = name;
this.nicename = nicename;
}
//重写string方法
@Override
public String toString() {
return "HeroList [no=" + no + ", name=" + name + ", nicename=" + nicename + "]";
}
}