-
Notifications
You must be signed in to change notification settings - Fork 0
/
MyStack.java
80 lines (68 loc) · 1.8 KB
/
MyStack.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
import java.util.EmptyStackException;
public class MyStack<T> {
private Node<T> top;
private int size;
// Constructor to initialize the stack
public MyStack() {
top = null;
size = 0;
}
// Node class to define the structure of each element in the stack
private static class Node<T> {
private T data;
private Node<T> next;
public Node(T data) {
this.data = data;
this.next = null;
}
}
// Push method to add an element to the top of the stack
public void push(T data) {
Node<T> newNode = new Node<>(data);
newNode.next = top;
top = newNode;
size++;
}
// Pop method to remove and return the element at the top of the stack
public T pop() {
if (isEmpty()) {
throw new EmptyStackException();
}
T data = top.data;
top = top.next;
size--;
return data;
}
// Peek method to return the element at the top of the stack without removing it
public T peek() {
if (isEmpty()) {
throw new EmptyStackException();
}
return top.data;
}
// Method to check if the stack is empty
public boolean isEmpty() {
return top == null;
}
public MyStack<T> duplicate() {
MyStack<T> copy = new MyStack<>();
Node<T> current = top;
while (current != null) {
copy.push(current.data);
current = current.next;
}
return copy;
}
// Method to return the size of the stack
public int size() {
return size;
}
public void Disply() {
Node p = top;
while (p!=null) {
System.out.println(p.data);
p=p.next;
}
}
// reverse stack
}