双向链表除头节点外,每个节点除data都有next和pre,next指向下一个节点的内存地址,pre指向上一个节点都内存地址,头节点,没有data,pre指向null,尾节点next记录的是null;
public class DoubleLinkedListDemo {
}
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;
}
}
/**
* 添加一个节点在链表的末尾
* @param heroNode
*/
public void add(HeroNode2 heroNode){
HeroNode2 temp = head;
while (true){
if(temp.next == null){
break;
}
temp = temp.next;
}
temp.next = heroNode;
heroNode.pre = temp;
}
/**
* 修改一个节点的数据
* @param newHeroNode
*/
public void update(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.println("没有找到编号,不能修改" + newHeroNode.no);
}
}
public void del(int no){
if(head.next == null){
System.out.println("链表空,无法删除");
return;
}
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;
}
}
}
}
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 "HeroNode2{" +
"no=" + no +
", name='" + name + '\'' +
", nickname='" + nickname + '\'' +
'}';
}
}