-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackUsingLink.cpp
More file actions
95 lines (83 loc) · 1.84 KB
/
StackUsingLink.cpp
File metadata and controls
95 lines (83 loc) · 1.84 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
#include <iostream>
class Node
{
private:
int m_data;
class Node *m_next;
public:
Node( int data=0,Node *next = nullptr)
: m_next{next} , m_data{data}{}
int isEmpty(){
if (this==NULL){
return 1;
}
else{
return 0;
}
}
int isFull(){
Node* p =new Node();
if(p==NULL){
return 1;
}
else{
return 0;
}
}
Node* push(int data);
Node* pop();
void display();
};
Node* Node::pop() // Time Complexity is O(1)
{
if (isEmpty())
{
printf("The stack is empty\n");
return this;
}
else
{
Node* current =this->m_next;
delete this;
return current;
}
}
Node* Node::push(int data) // Time Complexity is O(1)
{
if(isFull()){
std::cout<<"Stack Overflow";
return this;
}
else{
Node *another = new Node;
Node *current = another;
another->m_data=data;
another->m_next = this;
return current;
}
}
void Node::display() // Time Complexity is O(n)
{
Node *ptr = this;
while (ptr != NULL)
{
std::cout << "Element: " << ptr->m_data << std::endl;
ptr = ptr->m_next;
}
std::cout << std::endl;
}
int main()
{
Node *stact=nullptr; //stact has 1 data and NULL 1 ---> NULL
stact=stact->push(1); // now stact head has this 1 ---> 0 ---> NULL
stact=stact->push(2); // now stact head has this 2 ---> 1 ---> 0 ---> NULL
stact=stact->push(3); // this has changed the stact data to 3, 3 ---> 2 ---> 1 ---> 0 ---> NULL
// this will print the above just like in a stack, as
// | 3 |
// | 2 |
// | 1 |
// |__0__|
stact=stact->pop();
stact->display();
return 0;
}