forked from vatsalcode/LLM_Transformer_Queue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MyLinkedList.java
75 lines (74 loc) · 1.43 KB
/
MyLinkedList.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
public class MyLinkedList<E>{
Node head;
void add(E data) {
Node toAdd = new Node(data);
if(isEmpty()) {
head = toAdd;
return;
}
Node temp = head;
while(temp.next!=null) {
temp = temp.next;
}
temp.next = toAdd;
}
public boolean isEmpty(){
return head==null;
}
public E toRemove() throws Exception{
Node<E> temp = head;
if(isEmpty()) {
throw new Exception("Cannot delete from empty linked list.");
}
while(temp.next.next!=null) {
temp=temp.next;
}
Node<E> toDelete = temp.next;
temp.next = null;
return toDelete.data;
}
public E toRemoveQueue() throws Exception{
Node<E> temp = head;
if(isEmpty()) {
throw new Exception("Cannot remove from empty linked list");
}
if(temp.next==null) {
head = null;
return temp.data;
}
head = head.next;
return temp.data;
}
public E queueElement() throws Exception{
Node<E> temp = head;
if(isEmpty()) {
throw new Exception("Cannot view from empty linked list");
}
return temp.data;
}
public E toPeek() throws Exception{
Node<E> temp = head;
if(isEmpty()) {
throw new Exception("Cannot peek from empty linked list.");
}
while(temp.next!=null) {
temp = temp.next;
}
return temp.data;
}
void print() {
Node temp=head;
while(temp!=null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
}
static class Node<E>{
E data;
Node next;
public Node(E data) {
this.data = data;
next = null;
}
}
}