-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathData Structure - Linear (Stack).cpp
149 lines (122 loc) · 2.44 KB
/
Data Structure - Linear (Stack).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
// ConsoleApplication1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
class Node{
public:
int data;
Node* next;
Node(){
data = 0;
next = NULL;
};
};
class Stack{
Node *top;
public:
//Initialize Constractor
Stack(){
top = NULL;
};
//****Stack Operations****
//-1 Check if stack is empty or nah
bool isEmpty(){
if (top == NULL)return true;
else
return false;
};
//2- Check if stack is full or nah
bool isFull(){
Node *ptr = new Node();
if (ptr == NULL){
cout << "Stack is Full! \n";
return true;
};
};
//-3 Push Method - add items to stack
void push(int item){
if (isEmpty()){
//Check if node is empty
Node * newNode = new Node();
newNode->data = item;
newNode->next = NULL;
top = newNode;
}else{
//if node has items on stack
Node *newNode = new Node();
newNode->data = item;
newNode->next = top;
top = newNode;
}
};
//4- delete item from stack and return that removed item
int pop(){
Node* delPtr = top;
//to store removed item
int removedItem = top->data;
top = top->next;
delete delPtr;
return removedItem;
}
//5- Display Stack items (Traversing)
void display(){
Node *temp = top;
while (temp != NULL){
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
//6- Peek Method - Return the current value in stack (top value)
int peek(){
return top->data;
};
//7- Counter - Return Numbers of Stack items
int counter(){
int counter = 0;
Node*temp = top;
while (temp != NULL){
counter++;
temp = temp->next;
};
return counter;
};
//8- isFound Method - Check on specific value that founded on stack
bool isFound(int value){
bool found = false;
Node*temp = top;
while (temp != NULL){
if (temp->data == value){
found = true;
};
temp = temp->next;
};
return found;
};
};
int _tmain()
{
//create objecj from stack class
Stack stack;
int items;
for (int i = 0; i < 3; i++){
cout << "enter items number " << i+1 << " to push? \n";
cin >> items;
stack.push(items);
stack.display();
};
cout << stack.pop() << " removed from stack! \n";
stack.display();
int found;
cout << "enter item to search for ? \n";
cin >> found;
if (stack.isFound(found)){
cout << "item is found \n";
}else{
cout << "item not found \n";
};
cout << "stack has " <<stack.counter() << " items" << endl;
system("pause");
return 0;
}