-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathTrainComposition.cpp
126 lines (111 loc) · 2.61 KB
/
TrainComposition.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
// TestDome Quiz
// A TrainComposition is built by attaching and detaching wagons from the left and the right sides.
// For example, if we start by attaching wagon 7 from the left followed by attaching wagon 13, again from the left,
// we get a composition of two wagons (13 and 7 from left to right). Now the first wagon that can be detached from
// the right is 7 and the first that can be detached from the left is 13.
// Implement a TrainComposition that models this problem.
// Difficulty Level : Hard
// MaxTime : 20 min
// Passed all Test
#include <stdexcept>
#include <iostream>
using namespace std ;
class node{
public:
int value;
node* next,*prev;
node(int n=0){
value=n;
next=NULL;
prev=NULL;
}
};
class TrainComposition
{
node* first;
node* last;
public:
TrainComposition(){
first=last=NULL;
}
void attachWagonFromLeft(int wagonId)
{
node* newNode= new node(wagonId);
if(first==NULL){
first=last=newNode;
}
else{
first->prev=newNode;
newNode->next=first;
first=newNode;
}
}
void attachWagonFromRight(int wagonId)
{
node* newNode= new node(wagonId);
if(first==NULL){
first=last=newNode;
}
else{
newNode->prev=last;
last->next=newNode;
last=newNode;
}
}
int detachWagonFromLeft()
{
int n=-1;
if(first==NULL)
{
cout << "Underflow" ;
}
else if(first->next==NULL)
{
n=first->value;
delete first;
first=last=NULL;
}
else{
n=first->value;
node* temp;
temp=first;
first=first->next;
first->prev=NULL;
delete temp;
}
return n;
}
int detachWagonFromRight()
{
int n;
n=-1;
if(first==NULL)
{
cout << "Underflow" ;
}
else if(first->next==NULL)
{
n=first->value;
delete first;
first=last=NULL;
}
else{
n=last->value;
node* temp=last;
last=last->prev;
last->next=NULL;
delete temp;
}
return n;
}
};
#ifndef RunTests
int main()
{
TrainComposition tree;
tree.attachWagonFromLeft(7);
tree.attachWagonFromLeft(13);
cout << tree.detachWagonFromRight() << "\n"; // 7
cout << tree.detachWagonFromLeft(); // 13
}
#endif