-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack_by_LinkedList.cpp
149 lines (125 loc) · 3.05 KB
/
stack_by_LinkedList.cpp
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
140
141
142
143
144
145
146
147
148
149
#include <iostream>
using namespace std;
template<typename T>
struct Node{
T data;
Node<T> *next = NULL;
Node<T> *prev = NULL;
};
template<typename T>
class LinkedList{
private:
int size;
Node<T> *head, *tail;
public:
LinkedList(){
size = 0;
head = tail = NULL;
}
bool isEmpty(){return (size == 0);}
void add(T data, int idx){
if (size < idx){
cout << "Index error\n";
return;
}
Node<T> *newNode = new Node<T>();
newNode->data = data;
if (isEmpty()) head = tail = newNode;
else if (idx == 0){
head->prev = newNode;
newNode->next = head;
head = newNode;
}
else if (idx == size){
tail->next = newNode;
newNode->prev = tail;
tail = newNode;
}
else{
Node<T> *temp;
for (int i = 0; i < idx; i++) temp = temp->next;
temp->prev->next = newNode;
temp->next->prev = newNode;
}
size++;
}
T pop(int idx){
if (size <= idx) cout << "Index error\n";
else{
Node<T> *temp;
if (idx == 0){
if (size == 1) head = tail = NULL;
else{
temp = head;
head = head->next;
head->prev = NULL;
}
}
else if (idx == size - 1){
temp = tail;
tail = tail->prev;
tail->next = NULL;
}
else{
temp = head;
for (int i = 0; i < idx; i++) temp = temp->next;
temp->prev->next = temp->next;
temp->next->prev = temp->prev;
}
size--;
return temp->data;
}
}
Node<T> *operator[](int idx){
Node<T> *temp = head;
for (int i = 0; i < idx; i++) temp = temp->next;
return temp;
}
void Print(){
Node<T> *temp = head;
for (int i = 0; i < size; i++){
cout << temp->data << " ";
temp = temp->next;
}
cout << "\n";
}
};
template<typename T>
class Stack{
private:
int _top;
LinkedList<T> stack;
public:
Stack(){_top = -1;}
bool isEmpty() {return (_top == -1);}
void push(T data){
stack.add(data, ++_top);
}
T pop(){
if (isEmpty()) cout << "stack is Empty\n";
else return stack.pop(_top--);
}
T top(){
if (isEmpty()) printf("stack is Empty\n");
else return stack[_top]->data;
}
void Print(){
for (int i = 0; i <= _top; i++) cout << i << " ";
cout << "\n";
}
};
int main(){
Stack<int> st;
cout << st.isEmpty() << "\n";
cout << st.top() << "\n";
cout << st.pop() << "\n";
st.push(1);
st.push(2);
st.push(3);
st.push(4);
st.push(5);
cout << st.isEmpty() << "\n";
cout << st.top() << "\n";
cout << st.pop() << "\n";
st.Print();
}