-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathSinglyLinked.java
More file actions
53 lines (46 loc) · 1.06 KB
/
SinglyLinked.java
File metadata and controls
53 lines (46 loc) · 1.06 KB
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
class SinglyLinked {
static class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
private Node head;
public SinglyLinked() {
this.head = null;
}
public void append(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
return;
}
Node last = head;
while (last.next != null) {
last = last.next;
}
last.next = newNode;
}
public void printList() {
Node current = head;
while (current != null) {
System.out.print(current.data + " -> ");
current = current.next;
}
System.out.println("NULL");
}
public static void main(String[] args) {
SinglyLinked list = new SinglyLinked();
list.append(1);
list.append(2);
list.append(3);
list.printList(); // 输出:1 -> 2 -> 3 -> NULL
}
}
/*
jarry@MacBook-Pro linked % javac SinglyLinked.java
jarry@MacBook-Pro linked % java SinglyLinked
1 -> 2 -> 3 -> NULL
*/