-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmergable_stack_cpp.cpp
More file actions
108 lines (94 loc) · 1.79 KB
/
mergable_stack_cpp.cpp
File metadata and controls
108 lines (94 loc) · 1.79 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
#include<bits/stdc++.h>
using namespace std;
class node
{
public:
int num;
node* next;
};
class newstack
{
public:
node* head;
node* tail;
newstack()
{
head=NULL;
tail=NULL;
}
};
newstack* create()
{
newstack* stk=new newstack();
return stk;
}
void push(int num,newstack* stk)
{
node* temp=new node();
temp->num=num;
temp->next=stk->head;
if (stk->head==NULL)
{
stk->tail=temp;
}
stk->head=temp;
}
int pop(newstack* ms)
{
if (ms->head==NULL)
{
cout<<"stack underflow"<<endl;
return 0;
}
else
{
node* temp=ms->head;
ms->head=ms->head->next;
int popped=temp->num;
delete temp;
return popped;
}
}
void merge(newstack* ms1,newstack* ms2)
{
if(ms1->head==NULL)
{
ms1->head=ms2->head;
ms1->tail=ms2->tail;
return;
}
ms1->tail->next=ms2->head;
ms1->tail=ms2->tail;
}
void print(newstack* ms)
{
node* temp=ms->head;
while (temp!=NULL)
{
cout<<temp->num<<" ";
temp=temp->next;
}
}
int main()
{
newstack* stack1=create();
newstack* stack2=create();
int n1,n2,temp;
cout<<"enter sizes of both the stacks"<<endl;
cin>>n1>>n2;
cout<<"enter elements of 1st stack:"<<endl;
for(int i=1;i<=n1;i++)
{
cin>>temp;
push(temp,stack1);
}
cout<<"enter elements of 2nd stack:"<<endl;
for(int i=1;i<=n2;i++)
{
cin>>temp;
push(temp,stack2);
}
merge(stack1,stack2);
cout<<"The result after merging both stacks:"<<endl;
print(stack1);
}