-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSimpleListUsingNodeBuilderClass.java
71 lines (53 loc) · 1.52 KB
/
SimpleListUsingNodeBuilderClass.java
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
import java.util.*;
public class SimpleListUsingNodeBuilderClass {
public static void main(String[] args) {
ListBuilder listBuilder = new ListBuilder();
// inputs:
String[] inputStringArray = new String[]{"1", "2", "3", "4"};
List<String> inputElements = Arrays.asList(inputStringArray);
try {
listBuilder.createList(inputElements);
} catch(Exception ex) {
System.out.println("Exception recieved from ListBuilder: " + ex);
}
listBuilder.printList();
}
}
class ListBuilder {
Node headNode = null;
Node lastNode = null;
public void createList(List<String> elementsToBeAdded) throws Exception {
// list could be empty
if (elementsToBeAdded.isEmpty()) {
throw new Exception("Empty inputs");
}
// create the subsequent (HEAD) Nodes
for (int i=0; i<elementsToBeAdded.size(); i++) {
Node node = new Node();
node.value = elementsToBeAdded.get(i);
node.nextNode = null;
if (i == 0) {
headNode = node;
lastNode = node;
}
lastNode.nextNode = node;
lastNode = node;
}
}
public void addValueToList(String value) {
// check length of the input string?
}
public void printList() {
// empty list should not throw NPE or cause issues, handle it
// traverse the list, starting from the Headnode
Node node = headNode;
do {
System.out.println(node.value);
node = node.nextNode;
} while (!Objects.isNull(node));
}
}
class Node {
String value;
Node nextNode;
}