Skip to content

Commit 62bee68

Browse files
committed
single linked list
1 parent 64dee49 commit 62bee68

2 files changed

Lines changed: 106 additions & 0 deletions

File tree

src/ch03/exercises/e11/README.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# 3.11
2+
3+
## 题目
4+
5+
假设单链表使用一个头节点实现,但无尾节点,并假设它只保留对该节点的引用。编写一个类,包含
6+
7+
a. 返回链表大小的方法
8+
b. 打印链表的方法
9+
c. 测试值x是否含于链表的方法
10+
d. 如果值x尚未含于链表,添加值x到该链表的方法
11+
e. 如果值x含于链表,将x从该链表中删除的方法
12+
13+
## 答案
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
package ch03.exercises.e11;
2+
3+
/**
4+
* Created by cookfront on 2017/5/10.
5+
*/
6+
public class SingleLinkedList<AnyType> {
7+
private static class Node<AnyType> {
8+
public AnyType data;
9+
public Node<AnyType> next;
10+
11+
public Node(AnyType data, Node<AnyType> next) {
12+
this.data = data;
13+
this.next = next;
14+
}
15+
}
16+
17+
private Node<AnyType> head;
18+
private int theSize;
19+
20+
public boolean contains(AnyType x) {
21+
Node<AnyType> p = head.next;
22+
while (p != null) {
23+
if (x.equals(p.data)) {
24+
return true;
25+
}
26+
p = p.next;
27+
}
28+
return false;
29+
}
30+
31+
public void print() {
32+
Node<AnyType> p = head.next;
33+
while (p != null) {
34+
System.out.print(p.data + " ");
35+
p = p.next;
36+
}
37+
System.out.println();
38+
}
39+
40+
public int size() {
41+
return theSize;
42+
}
43+
44+
public boolean add(AnyType x) {
45+
if (contains(x)) {
46+
return false;
47+
}
48+
49+
Node<AnyType> p = new Node<>(x, head.next);
50+
head.next = p;
51+
theSize++;
52+
53+
return true;
54+
}
55+
56+
public boolean remove(AnyType x) {
57+
if (!contains(x)) {
58+
return false;
59+
}
60+
61+
Node<AnyType> prev = head;
62+
Node<AnyType> p = head.next;
63+
64+
while (!p.data.equals(x)) {
65+
prev = prev.next;
66+
p = p.next;
67+
}
68+
prev.next = p;
69+
theSize--;
70+
71+
return true;
72+
}
73+
74+
public static void main(String ...args) {
75+
SingleLinkedList<Integer> testList = new SingleLinkedList<>();
76+
77+
System.out.println("list size: " + testList.size());
78+
79+
testList.add(1);
80+
testList.add(2);
81+
testList.add(3);
82+
83+
testList.print();
84+
85+
if (testList.contains(3)) {
86+
System.out.println("test list have 3!");
87+
}
88+
89+
testList.remove(2);
90+
91+
testList.print();
92+
}
93+
}

0 commit comments

Comments
 (0)