0x01 定义
??双向链表:也叫双链表,是链表的一种,它的每个数据结点中都有两个指针,分别指向直接后继和直接前驱。
0x02 双向链表的优缺点
- 优点
– 对于链表中给定的一个结点,可以从两个方向进行操作; - 缺点
– 每个结点需要再添加一个额外的指针,需要更多的空间开销; – 节点的插入或删除更加费时(花更多的时间调整指针)。
0x03 双向链表的常用操作代码实现
package com.atCodeSun.doubleLinkedList04;
public class DoubleLinkedListDemo {
public static void main(String[] args) {
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 newHeroNode = new HeroNode2(4, "公孙胜", "入云龙");
doubleLinkedList.updata(newHeroNode);
System.out.println("修改结点~");
doubleLinkedList.list();
doubleLinkedList.del(3);
System.out.println("删除测试~");
doubleLinkedList.list();
}
}
class DoubleLinkedList{
private HeroNode2 head = new HeroNode2(0,"","");
public HeroNode2 getHead() {
return head;
}
public void list(){
if(head.next == null){
System.out.println("链表为空");
return;
}
HeroNode2 temp = head.next;
while(true){
if(temp == null){
break;
}
System.out.println(temp);
temp = temp.next;
}
}
public void add(HeroNode2 heroNode){
HeroNode2 temp = head;
while(true){
if(temp.next == null){
break;
}
temp = temp.next;
}
temp.next = heroNode;
heroNode.pre = temp;
}
public void updata(HeroNode2 newHeroNode){
if (head.next == null) {
System.out.println("链表为空~");
return;
}
HeroNode2 temp = head.next;
boolean flag = false;
while(true){
if(temp == null){
break;
}
if (temp.no == newHeroNode.no) {
flag = true;
break;
}
temp = temp.next;
}
if (flag) {
temp.name = newHeroNode.name;
temp.nickName = newHeroNode.nickName;
}else{
System.out.printf("没有找到编号为%d的结点,不能修改\n", newHeroNode.no);
}
}
public void del(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) {
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);
}
}
}
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;
}
@Override
public String toString() {
return "HeroNode{" +
"no=" + no +
", name='" + name + '\'' +
", nickName='" + nickName +
'}';
}
}
|