编程语言
首页 > 编程语言> > Java双链表

Java双链表

作者:互联网

一、概述

  

  

二、英雄类 

 1 class HeroNode {
 2     //值域
 3     public int id;
 4     public String name;
 5     public String nickName;
 6     //指针域
 7     public HeroNode next;
 8     public HeroNode prev;
 9 
10     HeroNode(int id, String name, String nickName) {
11         this.id = id;
12         this.name = name;
13         this.nickName = nickName;
14     }
15 }

三、主方法

1  @Test
2     public void test() {
3         //创建头结点
4         HeroNode head = new HeroNode(-1, null, null);
5         insertNode(head, new HeroNode(1, "松江", "及时雨"));
6         insertNode(head, new HeroNode(2, "武松", "行者"));
7         insertNode(head, new HeroNode(3, "林冲", "豹子头"));
8         printLinked(head);
9     }

四、操作

   双链表操作跟单链表相差无几,所以只写了插入和打印操作

  1、插入

 1 //插入新节点
 2     public void insertNode(HeroNode head, HeroNode newNode) {
 3         if (head == null) {
 4             System.out.println("头结点不能为空");
 5             return;
 6         }
 7         HeroNode hn = head;
 8         //循环到最后一个节点,它的next=null,即hn.next==null
 9         while (hn.next != null) {
10             hn = hn.next;
11         }
12         //将hn.next指向新节点
13         hn.next = newNode;
14         //新节点的prev指向hn,即新节点的前一个节点
15         newNode.prev = hn;
16     }

  2、打印

 1 //打印双向链表
 2     public void printLinked(HeroNode head) {
 3         if (head == null) {
 4             System.out.println("头结点不能为空");
 5             return;
 6         }
 7         if (head.next == null) {
 8             System.out.println("只有头结点,链表无数据");
 9             return;
10         }
11         HeroNode tmp = head;
12         System.out.println("头头头结点:" + convertNode(tmp));
13         while (tmp.next != null) {
14             System.out.println(show(tmp.next));
15             tmp = tmp.next;
16         }
17     }

  3、打印的辅助方法 

 1 public String show(HeroNode h) {
 2         return "{" +
 3                 "本节点id=" + convertNode(h) + '\'' +
 4                 "id=" + h.id +
 5                 ", name='" + h.name + '\'' +
 6                 ", nickName='" + h.nickName + '\'' +
 7                 ", prev=" + convertNode(h.prev) + '\'' +
 8                 ", next=" + convertNode(h.next) + '\'' +
 9                 '}' + "\n";
10     }
11 
12     //格式化HeroNode,直接输出地址值
13     public String convertNode(HeroNode h) {
14         return h == null ? null : h.toString().substring(h.toString().lastIndexOf('@'));
15     }

 

五、结果展示

  

 

标签:head,Java,HeroNode,next,hn,双链,null,public
来源: https://www.cnblogs.com/hyunbar/p/11264299.html