java双向链表结构_Java数据结构——双向链表

背景问题: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 + '\'' +

'}';

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值