java实现双向链表的基本功能
双向链表也叫双链表,是链表的一种,它的每个数据结点中都有两个指针,分别指向直接后继和直接前驱。所以,从双向链表中的任意一个结点开始,都可以很方便地访问它的前驱结点和后继结点
代码实现:
双向链表的添加结点和删除结点的方法和单向链表有所不同,具体看下方的代码
public class DoubleLInkedListDemo {
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 doublelist = new DoubleLinkedList();
doublelist.addLinkedList(hero1);
doublelist.addLinkedList(hero2);
doublelist.addLinkedList(hero3);
doublelist.addLinkedList(hero4);
System.out.println("双向链表的信息为:");
doublelist.showLinkedList();
System.out.println("双向链表跟新后的信息为:");
hero2.name = "小宋";
hero2.nickname = "下雨";
doublelist.update(hero2);
doublelist.showLinkedList();
System.out.println("删除某个结点后的信息为:");
doublelist.delet(hero2);
doublelist.showLinkedList();
}
}
class DoubleLinkedList {
HeroNode2 head = new HeroNode2(0, "", "");
public void addLinkedList(HeroNode2 hero) {
//创建一个辅助节点
HeroNode2 temp = head;
while (true) {
if (temp.next == null) {
break;
}
temp = temp.next;
}
temp.next = hero;
hero.pre = temp;
}
public void update(HeroNode2 hero) {
//首先判断链表是否为空
if (head.next == null) {
System.out.println("链表为空,修改数据失败。");
}
//创建辅助节点
HeroNode2 temp = head.next;
while (temp != null) {
if (temp.no == hero.no) {
temp.name = hero.name;
temp.nickname = hero.nickname;
break;
}
temp = temp.next;
}
}
//删除节点 根据编号进行删除节点,删除后的节点 idea的垃圾回收机制会进行回收
public void delet(HeroNode2 hero) {
HeroNode2 temp = head.next;
while (true) {
if (temp == null) {
System.out.println("链表为空,删除节点失败");
break;
}
if (temp.no == hero.no) {
temp.next.pre = temp.pre;
temp.pre.next = temp.next;
break;
}
temp = temp.next;
}
}
public void showLinkedList() {
if (head.next == null) {
System.out.println("链表为空。");
return;
}
HeroNode2 term = head.next;
while (true) {
System.out.println(term);
term = term.next;
if (term == null) {
break;
}
}
}
}
class HeroNode2 {
public int no;
public String name;
public String nickname;
HeroNode2 next;
HeroNode2 pre;
HeroNode2(int no, String name, String nickname) {
this.no = no;
this.name = name;
this.nickname = nickname;
}
@Override
public String toString() {
return "HeroNode{" +
"no=" + no +
", name='" + name + '\'' +
", nickname='" + nickname + '\'' +
'}';
}
}