思路分析
遍历
可以向前遍历也可以向后遍历
添加(默认添加到双向链表的最后)
1.先找到双向链表的最后这个节点;
2.temp.next = newHeroNode;
3.newHeroNode.pre = temp;
修改
和单向链表一样
删除
1.因为是双向链表,可以实现自我删除某个节点而不需要像单向列表一样找前面一个节点;
2.temp.pre.next = temp.next;
3.temp.next.pre = temp.pre;
代码实现
双向链表功能
package com.company;
public class DoubleLinkedList {
private HeroNode head = new HeroNode(0,"","");
public void add(HeroNode heroNode){
HeroNode temp = head;
while(true){
if(temp.next==null){
break;
}
temp = temp.next;
}
temp.next = heroNode;
heroNode.pre = temp;
}
public void list(){
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;
}
}
public void update(HeroNode heroNode){
if(head.next==null){
System.out.println("链表为空");
return;
}
HeroNode temp = head.next;
boolean flag = false;
while(true){
if(temp==null) break;
if(temp.no==heroNode.no){
flag = true;
break;
}
temp = temp.next;
}
if(flag){
temp.name = heroNode.name;
temp.nickname = heroNode.nickname;
}else {
System.out.println("The Hero doesn't existence!");
}
}
public void delete(int no){
HeroNode temp = head.next;
if(temp==null){
System.out.println("The list is empty!");
}
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.println("The Hero doesn't existence!");
}
}
}
双向链表结构
package com.company;
public class HeroNode {
public int no;
public String name;
public String nickname;
public HeroNode next;
public HeroNode pre;
public HeroNode(int no, String name, String nickname) {
this.no = no;
this.name = name;
this.nickname = nickname;
}
public String toString(){
return "HeroNode[no="+no+",name = "+name+",nickname = "+nickname+"]";
}
}