forked from dr-cs/intro-oop-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedList2.java
More file actions
89 lines (78 loc) · 2.27 KB
/
LinkedList2.java
File metadata and controls
89 lines (78 loc) · 2.27 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
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
public class LinkedList {
private class Node {
Object data;
Node next;
public Node(Object data, Node next) {
this.data = data;
this.next = next;
}
}
private Node front;
/**
* Add a new item to the front of this list.
*/
public void addFront(Object item) {
front = new Node(item, front);
}
/**
* Return the item at the front of this list and remove it from this list.
*/
public Object removeFront() {
if (null == front) {
throw new RuntimeException("Can't removeFront() on empty list.");
}
Object answer = front.data;
front = front.next;
return answer;
}
/**
* The number of items in this list.
*/
public int length() {
int len = 0;
Node node = front;
while (node != null) {
len++;
node = node.next;
}
return len;
}
/**
* @return true if this list has no elements, false otherwise.
*/
public boolean isEmpty() {
return front == null;
}
public String toString() {
StringBuffer sb = new StringBuffer("[");
for (Node node = front; node != null; node = node.next) {
sb.append(node.data + " ");
}
return sb.toString() + "]";
}
public void insertAfter(Object existingItem, Object newItem) {
Node curNode = front;
while (!curNode.data.equals(existingItem) &&
(curNode.next != null)) {
curNode = curNode.next;
}
Node newNode = new Node(newItem, curNode.next);
curNode.next = newNode;
}
public static void main(String[] args) {
LinkedList lst = new LinkedList();
lst.addFront("Thorny");
lst.addFront("Farva");
lst.addFront("Mac");
lst.addFront("Rabbit");
lst.addFront("Foster");
System.out.println(lst);
System.out.println("How many? " + lst.length());
lst.insertAfter("Rabbit", "Ursula");
System.out.println(lst);
System.out.println("How many? " + lst.length());
lst.insertAfter("Spread it on!", "Chimpo");
System.out.println(lst);
System.out.println("How many? " + lst.length());
}
}