1
+ /*
2
+ * A linked list is similar to an array, it holds values. However, links in a linked list do not have indexes.
3
+ * With a linked list you do not need to predetermine it's size as it grows and shrinks as it is edited.
4
+ * This is an example of a singly linked list. Elements can only be added/removed at the head/front of the list.
5
+ */
6
+ class LinkedList {
7
+ private Link head ; //Head refers to the front of the list
8
+
9
+ public LinkedList (){
10
+ head = null ;
11
+ }
12
+
13
+ public void insertHead (int x ){ //Insert an element at the head
14
+ Link newLink = new Link (x ); //Create a new link with a value attached to it
15
+ newLink .next = head ; //Set the new link to point to the current head
16
+ head = newLink ; //Now set the new link to be the head
17
+ }
18
+
19
+ public Link deleteHead (){ //Delete the element at the head
20
+ Link temp = head ;
21
+ head = head .next ; //Make the second element in the list the new head, the Java garbage collector will later remove the old head
22
+ return temp ;
23
+ }
24
+
25
+ public boolean isEmpty (){ //Returns true if list is empty
26
+ return (head == null );
27
+ }
28
+
29
+ public void display (){ //Prints contents of the list
30
+ Link current = head ;
31
+ while (current !=null ){
32
+ current .displayLink ();
33
+ current = current .next ;
34
+ }
35
+ System .out .println ();
36
+ }
37
+ }
38
+
39
+ class Link {
40
+ public int value ;
41
+ public Link next ; //This is what the link will point to
42
+
43
+ public Link (int valuein ){
44
+ value = valuein ;
45
+ }
46
+
47
+ public void displayLink (){
48
+ System .out .print (value +" " );
49
+ }
50
+ }
51
+
52
+ //Example
53
+ public class LinkedLists {
54
+ public static void main (String args []){
55
+ LinkedList myList = new LinkedList ();
56
+
57
+ System .out .println (myList .isEmpty ()); //Will print true
58
+
59
+ myList .insertHead (5 );
60
+ myList .insertHead (7 );
61
+ myList .insertHead (10 );
62
+
63
+ myList .display (); // 10(head) --> 7 --> 5
64
+
65
+ myList .deleteHead ();
66
+
67
+ myList .display (); // 7(head) --> 5
68
+ }
69
+ }
0 commit comments