-
Notifications
You must be signed in to change notification settings - Fork 134
/
Copy pathmergable stack.cpp
90 lines (77 loc) · 1.3 KB
/
mergable 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
#include <iostream>
using namespace std;
class node {
public:
int data;
node* next;
};
class mystack {
public:
node* head;
node* tail;
mystack()
{
head = NULL;
tail = NULL;
}
};
mystack* create()
{
mystack* ms = new mystack();
return ms;
}
void push(int data, mystack* ms)
{
node* temp = new node();
temp->data = data;
temp->next = ms->head;
if (ms->head == NULL)
ms->tail = temp;
ms->head = temp;
}
int pop(mystack* ms)
{
if (ms->head == NULL) {
cout << "stack underflow" << endl;
return 0;
}
else {
node* temp = ms->head;
ms->head = ms->head->next;
int popped = temp->data;
delete temp;
return popped;
}
}
void merge(mystack* ms1, mystack* ms2)
{
if (ms1->head == NULL)
{
ms1->head = ms2->head;
ms1->tail = ms2->tail;
return;
}
ms1->tail->next = ms2->head;
ms1->tail = ms2->tail;
}
void display(mystack* ms)
{
node* temp = ms->head;
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->next;
}
}
int main()
{
mystack* ms1 = create();
mystack* ms2 = create();
push(5, ms1);
push(10, ms1);
push(15, ms1);
push(20, ms2);
push(25, ms2);
push(30, ms2);
merge(ms1, ms2);
display(ms1);
}