-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCustomStack.java
More file actions
139 lines (115 loc) · 2.73 KB
/
Copy pathCustomStack.java
File metadata and controls
139 lines (115 loc) · 2.73 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
package CustomUtil.Stack;
public class CustomStack<E> implements CustomStackInterface<E> {
private Node<E> head;
private int size;
private static class Node<E> {
private final E element;
Node<E> next;
public Node(E element) {
this(element, null);
}
public Node(E element, Node<E> next) {
this.element = element;
this.next = next;
}
public E getElement() {
return this.element;
}
}
/*
* Adds element into the Stack
* At the top
* With O(1) TC
* */
public void push(E element) {
Node<E> newNode = new Node<>(element);
if(head == null) {
this.head = newNode;
this.size++;
return;
}
newNode.next = head;
this.head = newNode;
this.size++;
}
/*
* Removes top element from the Stack
* With O(1) TC
* */
public E pop() {
if(isEmpty()) {
return null;
}
E element = head.getElement();
this.head = head.next;
this.size--;
return element;
}
/*
* Retrieves the top element from the Stack
* With O(1) TC
* */
public E peek() {
if(isEmpty()) {
return null;
}
return head.getElement();
}
/*
* Checks if the Stack is empty or not
* return true if it does, Otherwise false
* */
public boolean isEmpty() {
return size == 0;
}
/*
* Returns the size of the Stack
* */
public int size() {
return this.size;
}
/*
* Removes every element from the Stack
* */
public void clear() {
this.head = null;
this.size = 0;
}
/*
* Checks if the specified element exists in the Stack Or not
* Returns true if it does, Otherwise false
* With O(n) TC
* */
public boolean contains(E element) {
if(isEmpty()) {
return false;
}
Node<E> currNode = head;
while(currNode.next != null) {
if(currNode.element.equals(element)) {
return true;
}
currNode = currNode.next;
}
return false;
}
@Override
public String toString() {
if(isEmpty()) {
return "[]";
}
StringBuilder res = new StringBuilder();
res.append("[");
Node<E> currNode = head;
int count = 0;
while(currNode != null) {
res.append(currNode.getElement());
if(++count < size) {
res.append(", ");
}
currNode = currNode.next;
}
res.append("]");
return res.toString();
}
}