public class DoubleLinkedListTest {
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.showList();
doubleLinkedList.update("韩统",5);
doubleLinkedList.update("林冲",5);
doubleLinkedList.del(1);
doubleLinkedList.showList();
}
}
//创建一个双向链表类
class DoubleLinkedList {
private heroNode2 head = new heroNode2(0,null,null);
private heroNode2 temp;
//返回头节点
public heroNode2 returnHead(){
return head;
}
//正向遍历链表
public void showList(){
heroNode2 temp = head.next;
if (head.next == null){
System.out.println("空链表");
return;
}
while (true){
if (temp!=null){
System.out.println(temp);
temp = temp.next;
}else {
break;
}
}
}
//添加(默认添加到末尾)
public void add(heroNode2 hero){
heroNode2 temp = head;
while (temp.next!=null){
temp = temp.next;
}
temp.next = hero;
hero.pre = temp;
}
//修改对应name的id
public void update(String name, int id){
temp = head.next;
if (head.next==null){
System.out.println("链表为空");
return;
}
while (true){
if (temp==null){ //应该首先判断是不是到链表末尾了
System.out.println("没有找到该英雄");
break;
}else if (temp.name==name){
temp.id = id;
break;
}else{
temp = temp.next;
}
}
}
//删除对应id的英雄节点
//与单向链表不同的是,双向链表删除时不用找到待删除的链表的前一个节点,找到待删除节点就可以进行自我删除
public void del(int id){
temp = head.next;
if (head.next==null){
System.out.println("链表为空");
return;
}
boolean flag = false;//判断是否找到节点
while (true){
if (temp==null){ //首先判断是不是到末尾了
System.out.println("未找到对应节点");
break;
}else if (temp.id == id){
flag = true;
break;
}else {
temp = temp.next;
}
}//while循环的作用是把temp指向对应待删除节点
if(flag){
if (temp.next==null){
temp.pre.next=temp.next;
}
if (temp.next!=null){
temp.pre.next=temp.next;
temp.next.pre = temp.pre;
}
}
}
}
class heroNode2{
public int id;//梁山排位
public String name;
public String nickname;
public heroNode2 pre = null;
public heroNode2 next = null;
public heroNode2(int id, String name, String nickname){
this.id = id;
this.name = name;
this.nickname = nickname;
}
@Override
public String toString() {
return "id:"+id+" "+"name:"+name+" "+"nickname:"+nickname;
}
}