-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.cpp
More file actions
120 lines (103 loc) · 1.81 KB
/
stack.cpp
File metadata and controls
120 lines (103 loc) · 1.81 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
#include<bits/stdc++.h>
using namespace std;
class Node{
public:
int data;
Node* next;
Node(){
this->data=INT_MIN;
this->next=NULL;
}
Node(int data){
this->data=data;
this->next=NULL;
}
};
class Stack{
Node* head;
int sz;
public:
Stack(){
this->head=NULL;
this->sz=0;
}
void push(int x);
int pop();
int top();
bool isEmpty();
int size();
};
void Stack::push(int x){
Node* newnode= new Node(x);
newnode->next=head;
head=newnode;
sz++;
}
int Stack::pop(){
if(head==NULL){
cout<<"Underflow ";
return INT_MIN;
}
int x=head->data;
Node* temp=head;
head=head->next;
sz--;
return x;
}
int Stack::top(){
if(head==NULL){
cout<<"Empty stack ";
return INT_MIN;
}
return head->data;
}
bool Stack::isEmpty(){
return head==NULL;
}
int Stack::size(){
return sz;
}
/*
Inbuilt stack
stack<dtype> name;
name.push(x);
name.pop() //pop return type is void
name.top()
name.size()
name.empty()
*/
bool checkParentheses(string str){
stack<char> s;
for(int i=0; i<str.size(); i++){
if(str[i]=='(' || str[i]=='{' || str[i]=='[')
s.push(str[i]);
if(str[i]==')' || str[i]=='}' || str[i]==']'){
if(s.empty())
return false;
char x=s.top();
s.pop();
if( (x=='(' && str[i]!=')') || (x=='{' && str[i]!='}') || (x=='[' && str[i]!=']'))
return false;
}
}
return s.empty();
}
int main(){
Stack stk;
while(1){
int ch;
cout<<"CHOICE: 1)Push 2)Pop 3)Top 4)isEmpty 5)Size 6)Break:"<<endl;
cin>>ch;
if(ch==1) {int x; cout<<"Element:"; cin>>x; stk.push(x);}
else if(ch==2) cout<<stk.pop()<<endl;
else if(ch==3) cout<<stk.top()<<endl;
else if(ch==4) cout<<stk.isEmpty()<<endl;
else if(ch==5) cout<<stk.size()<<endl;
else if(ch==6) break;
else cout<<"Invalid choice"<<endl;
}
// string str;
// cin>>str;
// cout<<checkParentheses(str);
return 0;
}