-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyLinkedList.java
More file actions
101 lines (90 loc) · 2.17 KB
/
MyLinkedList.java
File metadata and controls
101 lines (90 loc) · 2.17 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
90
91
92
93
94
95
96
97
98
99
100
public class MyLinkedList <E extends Comparable<E>> {
public MyNode<E> head;
//Purpose: No-arg constructor for MyLinkedList
//Gets: Nothing
public MyLinkedList() {
}
//Purpose: Adds an element to the head of the list
//Gets: E
//Returns: void
public void add(E element) {
MyNode<E> newNode = new MyNode<E>(element);
newNode.next = head;
head = newNode;
}
//Puropse: Returns whether or not an element exists in the list
//Gets: E
//Returns: boolean
public boolean find(E element) {
MyNode<E> current = head;
while(current != null) {
E currentElement = current.element;
if(currentElement.equals(element)) {
return true;
}
else {
current = current.next;
}
}
return false;
}
//Purpose: Insert an element before the given target element in the list
//Gets: E, E
//Returns: void
public void insertElementBefore(E targetElement, E insertElement) {
MyNode<E> current = head;
if(current.element.equals(targetElement)) {
add(insertElement);
}
else {
while(current.next != null) {
if(current.next.element.equals(targetElement)) {
MyNode<E> newNode = new MyNode<E>(insertElement);
newNode.next = current.next;
current.next = newNode;
return;
}
current = current.next;
}
}
}
//Purpose: Remove an element from the list
//Gets: E
//Returns: void
public void delete(E element) {
MyNode<E> current = head;
if(current.element.equals(element)) {
head = current.next;
}
else {
while(current.next != null) {
if(current.next.element.equals(element)) {
if(current.next.next == null) {
current.next = null;
return;
}
else {
//Next node in the list is skipped
current.next = current.next.next;
return;
}
}
current = current.next;
}
}
}
//Purpose: Return a String representation of the elements in the list
//Gets: Nothing
//Returns: String
@Override
public String toString() {
String list = "[";
MyNode<E> current = head;
while(current != null) {
//Close bracket if it is the end of the list
list += current.element.toString() + (current.next != null ? ", " : "]");
current = current.next;
}
return list;
}
}