Java实现单向双向链表原理分析

简介:

何为链表

链式结构是一种使用对象引用变量来创建对象间的链的数据结构。

对象引用变量可用于创建链式结构


对象引用变量所存储的特定地址一般无关紧要。换句话说,重要的是能够使用引用变量来访问对象,而对象在内存中的特定存储位置并不重要。因此,我们一般将引用变量描述为一个“指向”对象的名称,而不是显示其地址,按照这种理解,引用变量有时称为“指针”



一个指向对象的对象引用变量

下面的这个类就是一个链式结构:

1
2
3
4
5
6
public class Person {
private String name;
private String address;

private Person next; // Person对象的引用
}


这种类型的对象有时称为自引用对象。
这种关系构成了链表的基础。链表是一种链式结构,该结构中的每个对象都指向下一个对象,从而构成了链表中对象的线性次序。。链表中存储的对象一般称为链表的节点。

链表

注意,链表单独需要一个引用变量,用以表示其第一个结点。如果某个结点的next引用为null,则表示链表在该结点处终止

实现一个单向链表

插入结点


可能会在链表的任何位置插入一个结点:在链表的首部,或在链表中任何内部结点之间,或在链表的尾部。

(1)在首部插入结点
第一步,设置所添加结点的next引用,使其指向链表中当前的第一个结点。
第二步,重新设置指向链表首部的引用,使其指向这个新添加的结点。

在链表的首部插入一个结点

注意:如果上述这些步骤颠倒了,则将会遇到困难。如果首先重置front引用,则将失去这个唯一指向现有链表的引用,而且再也不能获取它。

(2)在其他部分插入结点
首先,设置新节点的next引用,使其指向current锁引用结点的下一个结点。然后,重新设置当前结点的next引用,使其指向这个新的结点。

在链表的中部插入一个结点

删除结点


对链表中的第一个结点的处理一般也比较特殊。
要删除链表的第一个结点,则要重新设置指向链表首部的引用,使其指向链表中当前的第二个结点。

删除链表的第一个结点

一旦找到索要删除的结点,则重新设置前一个结点的next引用,使其指向的结点与当前结点的next引用所指向的结点相同。然后,可以根据需要使用这个删除的结点。

删除链表内部结点

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
package chain;

/**
* Created by benjamin on 1/18/16.
* 单向链表的实现
*/

public class NodeList<E> {

private static class Node<E> {
E data;
Node<E> next;
public Node(E data, Node<E> next) {
this.data = data;
this.next = next;
}
}

/** 首元素的引用 **/
private Node<E> head;

/** 尾元素的引用 **/
private Node<E> last;

/** 其他元素的引用 **/
private Node<E> other;

/** list的元素个数 **/
private int size = 0;

/**
* 默认构造
*/

public NodeList() {
head = null;
last = head;
}

/**
* 构造一个有参数的list
* @param data 初始化参数
*/

public NodeList(E data) {
Node<E> d = new Node<>(data, null);
head = d;
last = head;
size++;
}

/**
* 增加一个数据到list中
* @param data 新增的数据
*/

public void add(E data) {
Node<E> d = new Node<>(data, null);
if (isEmpty()) {
head = d;
last = head;
} else {
last.next = d;
last = d;
}
size++;
}

/**
* 在index处添加元素data,其他元素后移
* @param index 元素索引,从0开始.
* @param data 新增元素
*/

public void add(int index, E data) {
checkIndex(index);

other = head;
if (index == 0) { //如果加在第一个,就把head的引用设为新元素对象
Node<E> d = new Node<>(data, other);
head = d;
} else {
for (int i = 0; i < index; i++) {
other = other.next;
}
Node<E> d = new Node<>(data, other.next);
other.next = d;
}
size++;
}

/**
* 替换原有的值为newValue
* @param oldValue 旧值
* @param newValue 新值
* @return 如果替换成功返回true, 否则返回false
*/

public boolean set(E oldValue, E newValue) {
other = head;
while (other != null) {
if (other.data.equals(oldValue)) {
other.data = newValue;
return true;
}
other = other.next;
}
return false;
}

/**
* 在指定的值后面插入一个新值
* @param specidiedData 指定的值
* @param newData 新值
* @return 如果插入成功返回true,否则返回false
*/

public boolean addAfter(E specidiedData, E newData) {
other = head;
while (other != null) {
if (other.data.equals(specidiedData)) {
Node<E> d = new Node<>(newData, other.next);
other.next = d;
size++;
return true;
}
other = other.next;
}
return false;
}

/**
* 根据索引, 获得此处的数据
* @param index 索引
* @return 获得的数据
*/

public E get(int index) {
checkIndex(index);
other = head;
for (int i = 0; i < index; i ++) {
other = other.next;
}
return other.data;
}

/**
* 删除list中存在的data
* @param data 要删除的数据
* @return 如果删除成功返回true,否则返回false
*/

public boolean remove(E data) {
other = head;
Node<E> pre = other;
for (int i = 0; i < size; i++) {
if (other.data.equals(data)) {
if (i == 0) {
head = other.next;
return true;
}
pre.next = other.next;
return true;
}
pre = other;
other = other.next;
}
return false;
}

/**
* 是否包含传入的元素
* @param data 传入的数据
* @return 如果存在返回true, 否则false
*/

public boolean contains(E data) {
other = head;
for (int i = 0; i < size; i++) {
if (other.data.equals(data)) {
return true;
}
}
return false;
}

private boolean isEmpty() {
return size == 0 || head == null;
}

/**
* 清空链表
*/

public void clear() {
head = null;
size = 0;
}

public void checkIndex(int index) {
if (index < 0 || index > size-1)
throw new IndexOutOfBoundsException("传入的索引无效: " + index);
}

/**
* 打印全部链表数据
*/

public void print() {
if (head == null || size == 0)
System.out.println("链表为空");
else {
other = head;
while (other != null) {
System.out.print(other.data + " ");
other = other.next;
}
System.out.println();
}
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package chain;

/**
* Created by piqiu on 1/18/16.
*/

public class NodeListTest {

public static void main(String[] args) {
NodeList<String> nodeList = new NodeList<>("first");
nodeList.add("a");
nodeList.add("b");
nodeList.add("c");
nodeList.print();

nodeList.add(2, "addNew");
nodeList.print();

nodeList.set("c", "C");
nodeList.print();

nodeList.addAfter("addNew", "addNew2");
nodeList.print();

System.out.println(nodeList.get(2));

nodeList.remove("addNew2");
nodeList.print();
nodeList.remove("first");
nodeList.print();

System.out.println(nodeList.contains("a"));
System.out.println(nodeList.contains("A"));

nodeList.clear();
nodeList.print();

/**
* first a b c
first a b addNew c
first a b addNew C
first a b addNew addNew2 C
b
first a b addNew C
a b addNew C
true
false
链表为空
*/

}
}

上面只是单向链表的简单实现。

实现一个双向链表


链式结构的另一种实现就是双向链表。双向链表维护两个引用:一个指向链表的第一个结点,另一个指向最后一个结点。链表中的每个结点都存储两个引用:一个指向下一个结点,另一个指向前一个结点。

下面是我仿着LinkedList写的双向链表。自己写完后发现很多地方原作者写的真是精妙,把增加元素、移除元素抽离出来,以及写法的精简、效率的考虑(利用索引构造结点处判断index是否小于size>>1),自己受益匪浅。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
package chain;

import java.io.Serializable;
import java.util.NoSuchElementException;

/**
* Created by benjamin on 1/18/16.
*/

public class LinkedList<E> implements Serializable {

private static final long serialVersionUID = -5635851059340344485L;

/**
* 结点类
* @param <E>
*/

private static class Node<E> {
E item;
Node<E> next;
Node<E> prev;

Node(Node<E> prev, E item, Node<E> next) {
this.prev = prev;
this.item = item;
this.next = next;
}
}

/** 第一个结点的引用 **/
transient Node<E> first;

/** 最后一个结点的引用 **/
transient Node<E> last;

/** list中元素的数目 **/
transient int size = 0;

/** 操作次数 **/
transient int modCount = 0;

public LinkedList() {
}

/**
* 把传入的元素变为第一个元素
* @param e
*/

private void linkFirst(E e) {
Node<E> f = first;
Node<E> newNode = new Node<>(null, e, f);
if (f == null)
last = newNode;
else
f.prev = newNode;
first = newNode;
size++;
modCount++;
}

/**
* 在最后面插入元素
* @param e
*/

private void linkLast(E e) {
Node<E> l = last;
Node<E> newNode = new Node<>(l, e, null);
if (l == null)
first = newNode;
else
l.next = newNode;
last = newNode;
size++;
modCount++;
}

/**
* 在指定结点之前插入元素
* @param e
* @param succ 指定结点
*/

private void linkBefore(E e, Node<E> succ) {
final Node<E> pred = succ.prev;
final Node<E> newNode = new Node<>(pred, e, succ);
succ.prev = newNode;
if (pred == null)
first = newNode;
else
pred.next = newNode;
size++;
modCount++;
}

/**
* 取消第一个结点的引用
*/

private E unlinkFirst(Node<E> f) {
final E element = f.item;
final Node<E> next = f.next;
f.item = null;
f.next = null;
first = next;
if (next == null)
last = null;
else
next.prev = null;
size--;
modCount++;
return element;
}

/**
* 取消最后一个结点的引用
* @param l
* @return 最后一个结点的值
*/

private E unlinkLast(Node<E> l) {
final E element = l.item;
final Node<E> pred = l.prev;
l.item = null;
l.prev = null;
last = pred;
if (pred == null)
first = null;
else
pred.next = null;
size--;
modCount++;
return element;
}

/**
* 取消结点x的引用
* @param x
* @return 取消的结点元素
*/

E unlink(Node<E> x) {
final E element = x.item;
final Node<E> next = x.next;
final Node<E> pred = x.prev;

// 如果是第一个
if (pred == null)
first = next;
else {
pred.next = next;
x.prev = null;
}

//如果是最后一个
if (next == null)
last = pred;
else {
next.prev = pred;
x.next = null;
}

x.item = null;
size--;
modCount++;
return element;
}

/**
* 取得第一个元素
* @return 第一个元素
*/

public E getFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return f.item;
}

/**
* 取得最后一个元素
* @return 最后一个元素
*/

public E getLast() {
final Node<E> l = last;
if (last == null)
throw new NoSuchElementException();
return l.item;
}

/**
* 删除第一个元素
* @return 第一个被删除的元素
*/

public E removeFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return unlinkFirst(f);
}

/**
* 删除最后一个元素
* @return 最后一个被删除的元素
*/

public E removeLast() {
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return unlinkLast(l);
}

/**
* 增加一个元素到list的第一个位置
* @param e
*/

public void addFirst(E e) {
linkFirst(e);
}

/**
* 增加一个元素到list的结尾
* @param e
*/

public void addLast(E e) {
linkLast(e);
}

/**
* 增加一个元素(默认增加在结尾)
* @param e
* @return true
*/

public boolean add(E e) {
linkLast(e);
return true;
}

/**
* 删除list中存在传入的对象
* @param o
* @return 如果改变了list,返回true,否则false
*/

public boolean remove(Object o) {
if (o == null) {
for (Node<E> x = first; x != null; x = x.next) {
if (x.item == null) {
unlink(x);
return true;
}
}
} else {
for (Node<E> x = first; x != null; x = x.next) {
if (o.equals(x.item)) {
unlink(x);
return true;
}
}
}
return false;
}

/**
* 清空list,所有引用对象置为null
*/

public void clear() {
for (Node<E> x = first; x != null; ) {
Node<E> next = x.next;
x.item = null;
x.prev = null;
x.next = null;
x = next;
}
first = null;
last = null;
size = 0;
modCount++;
}

/**
* 获取索引处的元素值
* @param index 索引
* @return 元素值
*/

public E get(int index) {
checkIndex(index);
return node(index).item;
}

/**
* 替换索引处的值为element
* @param index 索引
* @param element 新值
* @return 旧值
*/

public E set(int index, E element) {
checkIndex(index);
Node<E> oldNode = node(index);
E oldValue = oldNode.item;
oldNode.item = element;
return oldValue;
}

/**
* 在指定索引的地方插入元素element,原来的元素以及之后的元素后移
* @param index 插入元素的索引
* @param element 插入的元素
*/

public void add(int index, E element) {
checkIndex(index);

if (index == size)
linkLast(element);
else
linkBefore(element, node(index));
}

/**
* 移除索引处的元素
* @param index 索引
* @return 删除的元素
*/

public E remove(int index) {
checkIndex(index);
return unlink(node(index));
}

/**
* 获取对象在list中的索引
* @param o 要查找的对象
* @return 如果找到了对象,返回对应的索引值,否则返回-1
*/

public int indexOf(Object o) {
int index = 0;
if (o == null) {
for (Node<E> x = first; x != null; x = x.next) {
if (x.item == null)
return index;
index++;
}
} else {
for (Node<E> x = first; x != null; x = x.next) {
if (o.equals(x.item))
return index;
index++;
}
}
return -1;
}

/**
* 是否包含元素
* @param o
* @return 如果包含返回true
*/

public boolean contains(Object o) {
return indexOf(o) != -1;
}

/**
* 返回list中元素的大小
* @return 元素的大小
*/

public int getSize() {
return size;
}

/**
* 根据索引得到结点
* @param index 索引
* @return 结点
*/

Node<E> node(int index) {

// 如果是大小的一半之前,正序查找,否则倒序查找,提高效率
if (index < (size >> 1)) {
Node<E> f = first;
for (int i = 0; i < index; i++)
f = f.next;
return f;
} else {
Node<E> l = last;
for (int i = size - 1; i > index; i--)
l = l.prev;
return l;
}
}

/**
* 检查索引是否正确,不正确抛出 IndexOutOfBoundsException 异常
* @param index
*/

private void checkIndex(int index) {
if (!isElementIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}

/**
* 越界的错误信息
* @param index 越界的错误索引
* @return 越界的msg
*/

private String outOfBoundsMsg(int index) {
return "Index: " + index + ", Size: " + size;
}

/**
* 检查索引是否没有溢出
* @param index 索引
* @return 如果索引正确返回true
*/

private boolean isElementIndex(int index) {
return index >= 0 && index < size;
}
}
目录
相关文章
|
4天前
|
Java
【Java多线程】分析线程加锁导致的死锁问题以及解决方案
【Java多线程】分析线程加锁导致的死锁问题以及解决方案
12 1
|
4天前
|
算法 安全 Java
深入探索Java中的并发编程:CAS机制的原理与应用
总之,CAS机制是一种用于并发编程的原子操作,它通过比较内存中的值和预期值来实现多线程下的数据同步和互斥,从而提供了高效的并发控制。它在Java中被广泛应用于实现线程安全的数据结构和算法。
19 0
|
6天前
|
存储 监控 安全
JVM工作原理与实战(十六):运行时数据区-Java虚拟机栈
JVM作为Java程序的运行环境,其负责解释和执行字节码,管理内存,确保安全,支持多线程和提供性能监控工具,以及确保程序的跨平台运行。本文主要介绍了运行时数据区、Java虚拟机栈等内容。
11 0
|
7天前
|
搜索推荐 Java Shell
8大Java排序方法(由简入繁),有代码详解和原理指导
8大Java排序方法(由简入繁),有代码详解和原理指导
31 0
|
14天前
|
Java
JAVA循环结构分析与设计
JAVA循环结构分析与设计
20 1
|
14天前
|
存储 安全 Java
【Java EE】CAS原理和实现以及JUC中常见的类的使用
【Java EE】CAS原理和实现以及JUC中常见的类的使用
|
14天前
|
编解码 JavaScript 前端开发
【专栏】介绍了字符串Base64编解码的基本原理和在Java、Python、C++、JavaScript及Go等编程语言中的实现示例
【4月更文挑战第29天】本文介绍了字符串Base64编解码的基本原理和在Java、Python、C++、JavaScript及Go等编程语言中的实现示例。Base64编码将24位二进制数据转换为32位可打印字符,用“=”作填充。文中展示了各语言的编码解码代码,帮助开发者理解并应用于实际项目。
|
15天前
|
监控 搜索推荐 算法
Java排序:原理、实现与应用
【4月更文挑战第28天】本文探讨了Java中的排序算法,包括原理和实现。Java利用Comparator接口进行元素比较,通过Arrays和Collections类的sort方法对数组和列表进行排序。示例展示了使用这些方法的基本代码。此外,还讨论了冒泡排序算法和自定义排序场景,以适应不同需求。理解这些排序机制有助于提升程序效率。
13 1
|
16天前
|
网络协议 物联网 Java
Go与Java:在物联网领域的适用性分析
本文对比分析了Go和Java在物联网领域的适用性。Go语言因其轻量级、高效和并发特性,适合资源受限的物联网设备,特别是处理并发连接和数据流。Java则凭借跨平台性、丰富的生态系统和企业级应用能力,适用于大型物联网系统和复杂业务场景。两者在物联网领域各有优势,开发者可根据项目需求选择合适的语言。
|
16天前
|
设计模式 消息中间件 Java
Java 设计模式:探索发布-订阅模式的原理与应用
【4月更文挑战第27天】发布-订阅模式是一种消息传递范式,被广泛用于构建松散耦合的系统。在 Java 中,这种模式允许多个对象监听和响应感兴趣的事件。
35 2