Stack (Last-In-First-Out)
- pop(): remove the top item from the stack
- push(item): add an item to the top of the stack
- peek(): return the top of the stack
- isEmpty(): Return true if and only if the stack is empty
Stack Features:
- It does not offer constant-time access to the ith item. However, it does allow constant-time adds and removes, as it doesn't require shifting elements around.
public class MyStack<T> {
private static class StackNode<T> {
private T data;
private StackNode<T> next;
public StackNode(T data) {
this.data = data;
}
}
private StackNode<T> top;
public T pop() {
if (top == null) throw new EmptyStackException();
T item = top.data;
top = top.next;
return item;
}
public void push(T item) {
StackNode<T> t = new StackNode<>(item);
t.next = top;
top = t;
}
public T peek() {
if (top == null) throw new EmptyStackException();
return top.data;
}
public boolean isEmpty() {
return top == null;
}
}
Queue (First-In-First-Out)
- pop(): remove the top item from the stack
- push(item): add an item to the top of the stack
- peek(): return the top of the stack
- isEmpty(): Return true if and only if the stack is empty
public class MyQueue<T> {
private static class QueueNode<T> {
private T data;
private QueueNode<T> next;
public QueueNode(T data) {
this.data = data;
}
}
private QueueNode<T> first;
private QueueNode<T> last;
public void add(T item) {
QueueNode<T> t = new QueueNode<T>(item);
if (last != null){
last.next = t;
}
last = t;
if (first == null) {
first = last;
}
}
public T remove() {
if (first == null) throw new NoSuchElementException();
T data = first.data;
first = first.next;
if (first == null) {
last = null;
}
return data;
}
public T peek() {
if (first == null) throw new NoSuchElementException();
return first.data;
}
public boolean isEmpty() {
return first == null;
}
}
'Algorithms and Data Structures > Data Structures' 카테고리의 다른 글
[Data Structures] Binary Tree Traversals with Implementations (0) | 2022.05.25 |
---|---|
[Data Structures] Trees (BT, BST) (0) | 2022.05.24 |
[LinkedList] CCI 2.2-2.3 (0) | 2022.05.21 |
[Data Structures] Linked List (0) | 2022.05.20 |
[Data Structures] Arrays and Strings (0) | 2022.05.18 |