-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.cpp
More file actions
114 lines (101 loc) · 1.92 KB
/
Stack.cpp
File metadata and controls
114 lines (101 loc) · 1.92 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
#include <cstdlib>
#include<stdio.h>
#include<iostream>
using namespace std;
class Node{
public:
Node *next;
int data;
};
class Stack{
public:
Node *head;
Stack(){head=NULL;}
Node * Head(){return head;}
int pop();
void push(int d);
void displayStack(){
Node *temp;
if(head==NULL){
cout<<"The Stack is empty"<<endl;
}
else{
temp=head;
while(temp!=NULL){
cout<<temp->data<<"\t";
temp=temp->next;
}
}
cout<<endl;
}
};
int Stack:: pop(){
// remove the last value in the stack
int value=0;
Node *temp=head;
Node * temp2;
if(temp==NULL){ // when stack is empty
cout<<"The Stack is empty"<<endl;
}
else{
if(temp->next==NULL){ // popping the head
value=temp->data;
head=NULL;
delete temp;
}
else{
while(temp->next->next!=NULL){
temp=temp->next;
}
value=temp->next->data;
temp2=temp->next;
temp->next=NULL;
delete temp2;
}
}
return value;
}
void Stack:: push(int d){
Node *n=new Node;
Node *temp;
if(head==NULL){ // pushing to the head
head=n;
head->data=d;
head->next=NULL;
}
else{ // pushing everywhere else
temp=head;
while(temp->next!=NULL){temp=temp->next;}
temp->next=n;
temp=temp->next;
temp->data=d;
temp->next=NULL;
}
}
/*int main(int argc, char** argv) {
Stack obj;
int choice=0,value=0;
while(choice !=4){
cout<<"1-POP 2-PUSH 3-DISPLAY 4-EXIT"<<endl;
cin>>choice;
switch(choice){
case 1:{
value=obj.pop();
cout<<"Popped value="<<value<<endl;
break;
}
case 2:{
cout<<"Enter the value to push"<<endl;
cin>>value;
obj.push(value);
break;
}
case 3:{
cout<<"Stack contains:"<<endl;
obj.displayStack();
break;
}
}
}
return 0;
}*/