背景问题:1、管理单向链表查找的方向只能有一个。
2、单向链表不能自我删除,删除不方便
双向链表示意图
注意:每一个双向链表都有两个头节点,一个pre(指向前一个节点);next(指向后一个节点)
双向链表的增删改查
增加数据:
思路:1、先遍历双线链表找到最后一个节点(temp)
2、temp.next = newHeroNode
3、newHeroNode.pre = temp
删除数据:
思路:遍历双向链表,找到要删除的节点(temp)
temp.pre.next = temp.next
temp.next.pre = temp.pre
注意:第二步与第三步道理相同,很好理解,先找到temp的前一个节点tempPre 把前一个节点的next改成temp的限一个节点(tempNext)
查找数据:
思路:直接遍历双向链表找到要查找数组的编号
修改数据:
思路:1、直接遍历双向链表找到要查找数组的编号
2、temp.name = ???
代码实现
public class DoubleLinkedListText {
public static void main(String[] args) {
DoublieLinkedList dll = new DoublieLinkedList();
HeroNode h1 = new HeroNode(1,"刘玄德");
HeroNode h2 = new HeroNode(2,"关云长");
HeroNode h3 = new HeroNode(3,"张翼德");
HeroNode h4 = new HeroNode(4,"诸葛亮");
dll.add(h1);
dll.add(h2);
dll.add(h3);
dll.add(h4);
dll.showAll();
dll.delete(3);
dll.showAll();
}
}
class DoublieLinkedList{
private static HeroNode head = new HeroNode(0,"");
public static HeroNode getHead() {
return head;
}
//添加英雄
/*
* 1、遍历链表找到最后这个节点temp
* 2、temp.next = herpNode
* 3、heroNode.pre = temp*/
public void add(HeroNode heroNode){
HeroNode temp = head;
while (true){
//找到最后那个节点
if (temp.next==null){
temp.next = heroNode;
heroNode.pre = temp ;
break;
}
temp = temp.next;
}
}
//按顺序添加英雄
/*
* */
//删除英雄
/*
* 1、遍历链表,找到编号为num的节点temp
* 2、temp.pre.next = temp.next
* 3、temp.next.pre = temp.pre
* */
public void delete(int num){
if (head.next==null){
System.out.println("链表为空!");
}
HeroNode temp = head.next;
while (true){
if (temp.num == num){
temp.pre.next = temp.next;
temp.next.pre = temp.pre;
break;
}
temp = temp.next;
}
}
//遍历链表
public void showAll(){
if (head.next==null){
System.out.println("链表为空!");
return;
}
HeroNode temp = head.next;
while (true){
if (temp==null){
break;
}
System.out.println(temp);
temp = temp.next;
}
}
}
class HeroNode{
public int num;
public String name ;
public HeroNode pre;
public HeroNode next ;
//构造函数
public HeroNode(int num,String name){
this.num = num ;
this.name = name;
}
//重写toString方法
@Override
public String toString() {
return "HeroNode{" +
"num=" + num +
", name='" + name + '\'' +
'}';
}
}