-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedList.java
More file actions
85 lines (70 loc) · 1.53 KB
/
LinkedList.java
File metadata and controls
85 lines (70 loc) · 1.53 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
/**
* Implements the Linked List class.
*/
package linkedlist;
//Class for storing linked list.
public class LinkedList<K> {
// Value of the node
public K value = null;
public int size = 0;
// Link to the next element
public LinkedList<K> next;
/**
* Constructor of linked list.
* @param value The value of the first node.
*/
public LinkedList(K value) {
this.value = value;
size = 1;
}
/**
* Constructor of linked list.
* @param value The value of the first node.
*/
public LinkedList() {}
/**
* Adds new value to the linked list by
* adding to in front of all other values.
* @param value The value to add.
*/
public void push(K value) {
size++;
if (size == 1) {
this.value = value;
return;
}
LinkedList<K> second = new LinkedList<K>(this.value);
second.next = this.next;
this.value = value;
this.next = second;
}
/**
* Removes the first element and returns it's value.
* @return Value of the top element.
*/
public K pop() {
K result = this.value;
size--;
if (this.next == null) {
this.value = null;
return result;
}
this.value = this.next.value;
this.next = this.next.next;
return result;
}
/**
* Returning printable version of the linked list.
*/
@Override
public String toString() {
if (this.value == null) {
return "null";
}
if (this.next == null) {
return this.value.toString();
} else {
return this.value + " -> " + this.next;
}
}
}