双链表的增删改查
/**
* 双链表增删改查
*/
class DoubleLinkedList {
HeroNode head = new HeroNode();
/**
* 添加节点
* @param heroNode
*/
public void add(HeroNode heroNode) {
HeroNode temp = head;
while (true) {
if (temp.next == null) {
temp.next = heroNode;
heroNode.pre = temp;
break;
}
temp = temp.next;
}
}
/**
* 双链表可以自我删除
* @param heroNode
*/
public void del(HeroNode heroNode) {
if (head.next == null) {
throw new NullPointerException("链表为空,不可删除");
}
HeroNode temp = head.next;
while (true) {
if (temp == null) {
throw new NullPointerException("未找到该节点");
}
if (temp.no == heroNode.no) {
// 避免是最后一个节点
temp.pre.next = temp.next;
if (temp.next != null) {
temp.next.pre = temp.pre;
}
return;
}
temp = temp.next;
}
}
/**
* 修改节点
* @param heroNode
*/
public void update(HeroNode heroNode) {
if (head.next == null) {
throw new NullPointerException("链表为空,不可修改");
}
HeroNode temp = head.next;
while (true) {
if (temp == null) {
throw new NullPointerException("未找到该节点");
}
if (temp.no == heroNode.no) {
temp.name = heroNode.name;
break;
}
temp = temp.next;
}
}
/**
* 遍历双链表
*/
public void show() {
if (head.next == null) {
throw new NullPointerException("链表为空,不可遍历");
}
HeroNode temp = head.next;
while (true) {
if (temp == null) {
break;
}
System.out.println(temp);
temp = temp.next;
}
}
/**
* 静态内部类双链表节点
*/
static class HeroNode {
public int no;
public String name;
public HeroNode next;
public HeroNode pre;
public HeroNode() {
}
public HeroNode(int no, String name) {
this.no = no;
this.name = name;
}
@Override
public String toString() {
return "HeroNode{" +
"no=" + no +
", name='" + name + '\'' +
'}';
}
}
}