This repository has been archived by the owner on Jan 28, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinkedList.java
84 lines (68 loc) · 2.12 KB
/
LinkedList.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
72
73
74
75
76
77
78
79
80
81
82
83
84
/**
* Jaired Jawed
* Dec 10, 2017
* LinkedList.java
*/
import java.util.ArrayList;
public class LinkedList<T> {
private int numberOfNodes = 0;
private ListNode<T> front = null;
// Returns true if the linked list has no nodes, or false otherwise.
public boolean isEmpty() {
return (front == null);
}
// Deletes all of the nodes in the linked list.
// Note: ListNode objects will be automatically garbage collected by JVM.
public void makeEmpty() {
front = null;
numberOfNodes = 0;
}
// Returns the number of nodes in the linked list
public int size() {
return numberOfNodes;
}
// Adds a node to the front of the linked list.
public void addFront( T element ) {
front = new ListNode<T>( element, front );
numberOfNodes++;
}
// Returns a reference to the data in the first node, or null if the list is empty.
public T peek() {
if (isEmpty())
return null;
return front.getData();
}
// Removes a node from the front of the linked list (if there is one).
// Returns a reference to the data in the first node, or null if the list is empty.
@SuppressWarnings("unchecked")
public T removeFront() {
T tempData;
if (isEmpty())
return null;
tempData = front.getData();
front = front.getNext();
numberOfNodes--;
return tempData;
}
@SuppressWarnings("unchecked")
public void removeEnd(T element) {
ListNode<T> node=front;
while(node.getNext() != null)
{
node = node.getNext();
}
node.setNext(new ListNode<T>((T)element, null));
}
// Return array filled with T objects
@SuppressWarnings("unchecked")
public ArrayList<T> getArray() {
ArrayList<T> shapeArray=new ArrayList<T>();
ListNode<T> node=front;
while (node!=null)
{
shapeArray.add(node.getData());
node = node.getNext();
}
return shapeArray;
}
}