心在山东身在吴,飘蓬江海漫嗟吁。

他时若遂凌云志, 敢笑黄巢不丈夫。

               ——水浒传

先上源代码,LinkedList类:

 1 private static class Node<E> {
 2         E item;
 3         Node<E> next;
 4         Node<E> prev;
 5 
 6         Node(Node<E> prev, E element, Node<E> next) {
 7             this.item = element;
 8             this.next = next;
 9             this.prev = prev;
10         }
11     }

Java链表中定义了一个内部类Node类,"node"是节点的意思.链表的基本元素是节点,(双向链表)每个节点包含三个成员,分别是item:数据,next:指向链表下一个元素的指针,prev:指向上一个元素的指针

先看一下C中的链表:

Java学习笔记--链表

头指针变量保存了一个地址,它指向一个变量No.1,No.1中又保存了一个指针,它指向No.2,以此类推,直到No.X中保存的地址指向No.last,图中最后一项为No.3,它指向NULL。

双向链表每个元素中又加入了prev指针。

双向链表图:

Java学习笔记--链表

但是java中没有指向内存地址的指针,那么如何实现链表呢?

再看Java源代码:

 1  transient int size = 0;
 2 
 3     /**
 4      * Pointer to first node.
 5      * Invariant: (first == null && last == null) ||
 6      *            (first.prev == null && first.item != null)
 7      */
 8     transient Node<E> first;
 9 
10     /**
11      * Pointer to last node.
12      * Invariant: (first == null && last == null) ||
13      *            (last.next == null && last.item != null)
14      */
15     transient Node<E> last;
16 
17     /**
18      * Constructs an empty list.
19      */
20     public LinkedList() {
21     }
22 
23     /**
24      * Constructs a list containing the elements of the specified
25      * collection, in the order they are returned by the collection's
26      * iterator.
27      *
28      * @param  c the collection whose elements are to be placed into this list
29      * @throws NullPointerException if the specified collection is null
30      */
31     public LinkedList(Collection<? extends E> c) {
32         this();
33         addAll(c);
34     }
View Code

相关文章:

  • 2021-05-18
  • 2022-02-05
  • 2022-02-06
  • 2021-11-27
  • 2022-03-03
  • 2021-09-10
  • 2021-04-13
猜你喜欢
  • 2021-08-14
  • 2022-02-12
  • 2022-12-23
  • 2022-12-23
  • 2021-06-05
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案