-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.cpp
50 lines (44 loc) · 860 Bytes
/
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
#include "stack.h"
Node::Node(const int data)
{
this->data = data;
this->next = nullptr;
}
Stack::Stack(){ head = nullptr; }
Stack::~Stack(){ while (!empty()) pop(); }
void Stack::push(const int data)
{
Node *n = new (std::nothrow) Node(data);
if (NULL == n)
{
throw(std::invalid_argument("allocation error"));
}
if (NULL == head)
head = n;
else
{
n->next = head;
head = n;
}
}
int Stack::pop()
{
if (empty())
{
throw(std::invalid_argument("error - bad expression"));
}
Node* temp = head;
int out = temp->data;
head = head->next;
delete temp;
return out;
}
int Stack::top() const
{
if (empty())
{
throw(std::invalid_argument("error - bad expression"));
}
return head->data;
}
int Stack::empty() const { return NULL == head; }