链表的组成:链表头+结点
链表头一般只存储下一个节点的引用
节点:存数据+下一个节点的引用
链表头代码:
|
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
|
package
com.xingej.algorithm.datastructure.linkedList.singleLinkedList;
/**
* 声明一个链表的头部
*
* 从链表头的使用,联想到hadoop,spark,netty中都有上下文context
*
* @author erjun 2017年12月8日 上午8:45:08
*/
public
class
LinkList {
private
Node first;
public
LinkList() {
// 初始链表时,指针引用为空
first =
null
;
}
public
void
insertFirst(
int
iData,
double
dData) {
// 创建一个新的链节点
Node newLink =
new
Node(iData, dData);
// 更新新创建的链节点next引用,也就是将头部引用,赋值给它
newLink.next = first;
// 更新链表头部的引用, 也就是将新创建的链节点的引用,赋值给头部引用
first = newLink;
}
public
boolean
isEmpty() {
return
null
== first;
}
public
Node deleteFirst() {
// 先缓存 被删除的第一个元素
Node temp = first;
// 链表,这种数据结构里,删除元素,只需要更新指针引用就可以了
// 更新头部元素的引用
first = first.next;
return
temp;
}
public
void
displayList() {
System.out.println(
"List (first--->last):"
);
Node current = first;
while
(
null
!= current) {
current.displayLink();
// 获取下一个元素的引用, 在C语言里,称为指针
current = current.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
|
package
com.xingej.algorithm.datastructure.linkedList.singleLinkedList;
/**
* 声明一个节点
*
* @author erjun 2017年12月8日 上午8:41:50
*/
public
class
Node {
private
int
iData;
private
double
dData;
// 不是private 哦,不然对象访问不了
public
Node next;
public
Node(
int
iData,
double
dData) {
this
.dData = dData;
this
.iData = iData;
}
public
void
displayLink() {
System.out.println(
"{"
+ iData +
", "
+ dData +
"}"
);
}
}
|
简单测试用例:
|
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
|
package
com.xingej.algorithm.datastructure.linkedList.singleLinkedList;
import
org.junit.Test;
/**
* 单链表测试
*
* @author erjun 2017年12月8日 上午9:00:54
*/
public
class
LinkListTest {
@Test
public
void
test() {
LinkList list =
new
LinkList();
// 很明显,每次都是插入链表的第一个元素
list.insertFirst(
32
,
8
);
list.insertFirst(
3
,
3
);
list.insertFirst(
2
,
6
);
list.insertFirst(
42
,
8
);
list.insertFirst(
26
,
9
);
list.displayList();
}
}
|


本文转自故新51CTO博客,原文链接: http://blog.51cto.com/xingej/2048729,如需转载请自行联系原作者