forked from krishnamanojpvr/DSCPP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
38_Stack_LinkedList.cpp
95 lines (87 loc) · 1.54 KB
/
38_Stack_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
#include<iostream>
using namespace std;
class Node{
public:
int data;
Node *next=NULL;
Node(int data){
this->data = data;
this->next = NULL;
}
};
class Stack{
Node * top;
public:
Stack(int data){
Node *newnode = new Node(data);
top = newnode;
}
Stack(){
top = NULL;
}
void Push(int data);
void Pop();
int Peek();
bool isEmpty();
int Length();
void Display();
};
void Stack::Push(int data){
Node *newnode = new Node(data);
newnode->next = top;
top = newnode;
}
void Stack::Pop(){
Node * temp = top;
top = temp->next;
delete temp;
}
int Stack::Peek(){
return top->data;
}
bool Stack::isEmpty(){
if(top == NULL){
return true;
}
return false;
}
int Stack::Length(){
if(top == NULL){
return 0;
}
int count = 0;
Node *temp = top;
while(temp!=NULL){
count++;
temp = temp->next;
}
return count;
}
void Stack::Display(){
if(top==NULL){
cout<<"Stack Underflow";
return;
}
Node *temp = top;
while(temp->next!=NULL){
cout<<temp->data<<"->";
temp = temp->next;
}
cout<<temp->data<<endl;
}
int main()
{
Stack s1(10);
s1.Display();
s1.Push(20);
s1.Display();
cout<<"Length : "<<s1.Length()<<endl;
cout<<"Top : "<<s1.Peek()<<endl;
s1.Push(30);
s1.Push(40);
s1.Display();
s1.Pop();
s1.Display();
cout<<"Length : "<<s1.Length()<<endl;
return 0;
}