1
+
2
+ import java .util .NoSuchElementException ;
3
+
4
+ class Node {
5
+ int value ;
6
+ Node next ;
7
+ public Node (int value , Node next ) {
8
+ this .value = value ;
9
+ this .next = next ;
10
+ }
11
+ }
12
+ class LinkedList {
13
+ Node root ;
14
+ public LinkedList () {
15
+ this .root = null ;
16
+ }
17
+ /**
18
+ * Adds the value to the _beginning_ of the list
19
+ * @param value
20
+ */
21
+ public void prepend (int value ) {
22
+ // Just add at the beginning
23
+ this .root = new Node (value , this .root );
24
+ }
25
+ /**
26
+ * Adds the value to the _end_ of the list
27
+ * @param value
28
+ */
29
+ public void append (int value ) {
30
+ if (this .root == null ) {
31
+ this .root = new Node (value , null );
32
+ return ;
33
+ }
34
+ // If it's just one element, add if after that one
35
+ Node n = this .root ;
36
+ if (n .next == null ) {
37
+ n .next = new Node (value , null );
38
+ return ;
39
+ }
40
+ // Otherwise, loop until the end and add at the end with a null
41
+ while (n .next != null ) {
42
+ n = n .next ;
43
+ n .next = new Node (value , null );
44
+ }
45
+ }
46
+ /**
47
+ * @return the value of the first element in the list
48
+ */
49
+ public int first () {
50
+ return this .root .value ;
51
+ }
52
+ /**
53
+ * @return the value of the last element in the list
54
+ */
55
+ public int last () {
56
+ Node n = this .root ;
57
+ // If no such element, throw an exception
58
+ if (n == null ) { throw new NoSuchElementException (); }
59
+ // If it's just one element, return its value
60
+ if (n .next == null ) { return n .value ; }
61
+ // Otherwise, search for the end of the list and return the last value
62
+ while (n .next != null ) {
63
+ n = n .next ;
64
+ }
65
+ return n .value ;
66
+ }
67
+ /**
68
+ * @return a string representation of the list
69
+ */
70
+ public String toString () {
71
+ Node n = this .root ;
72
+ String s = "" ;
73
+ while (n != null ) {
74
+ s += n .value + " " ;
75
+ n = n .next ;
76
+ }
77
+ return s ;
78
+ }
79
+ /**
80
+ * @return the number of elements in the list
81
+ */
82
+ public int length () {
83
+ Node n = this .root ;
84
+ int i = 0 ;
85
+ while (n != null ) {
86
+ i += 1 ;
87
+ n = n .next ;
88
+ }
89
+ return i ;
90
+ }
91
+ }
0 commit comments