/*
• 双向链表
*/
public class DoubleLinkedListDemo {
public static void main(String[] args) {
HeroNode2 hero1 = new HeroNode2(1, "宋江", "及时雨");
HeroNode2 hero2 = new HeroNode2(2, "卢俊义", "玉麒麟");
HeroNode2 hero3 = new HeroNode2(3, "吴用", "智多星");
DoubleLinkedList doublelist = new DoubleLinkedList();
doublelist.addNode(hero1);
doublelist.addNode(hero2);
doublelist.addNode(hero3);
//doublelist.findNode(1);
doublelist.listNode();
}
}
class DoubleLinkedList {
private HeroNode2 head = new HeroNode2(0,"","");// 头结点
public HeroNode2 getHead() {
return head;
}
// 添加节点
public void addNode(HeroNode2 hero) {
HeroNode2 temp = head;
while (true) {
if (temp.next == null) {
break;
}
temp = temp.next;
}
// 形成关联
temp.next = hero;
hero.pre = temp;
}
// 删除结点
public void deleteNode(int no) {
HeroNode2 temp = head;
boolean flag = false;
while (true) {
if (temp == null) {
break;
}
if (temp.no == no) {
flag = true;
break;
}
temp = temp.next;// 后移
}
if (flag) {
temp.next = temp.next.next;
temp.pre.pre = temp;
} else {
System.out.printf("您所要删除%d的结点不存在\n", no);
}
}
// 更新結點
public void updateNode(HeroNode2 hero) {
HeroNode2 temp = head;
boolean flag = false;
while (true) {
if (temp == null) {
break;
}
if (temp.no == hero.no) {
flag = true;
break;
}
temp = temp.next;
}
if (flag) {
temp.name = hero.name;
temp.nickname = hero.nickname;
} else {
System.out.printf("您所要修该%d的结点不存在\n", hero.no);
}
}
// 查找結點
public void findNode(int no) {
HeroNode2 temp = head;
boolean flag = false;
while (true) {
if (temp == null) {
break;
}
if (temp.no == no) {
flag = true;
break;
}
temp = temp.next;
}
if (flag) {
System.out.println(temp);
} else {
System.out.println("您所查找的结点不存在");
}
}
// 遍历结点
public void listNode() {
if (head.next == null) {
System.out.println("链表为空");
return;
}
HeroNode2 temp = head.next;
while (true) {
if (temp == null) {
break;
} else {
System.out.println(temp);
}
temp=temp.next;
}
}
}