Home / utk / cs140 / sp19 / live_codings_in_lab / part1_concepts / stack_non_templated / stack.cpp
Directory Listing
main.cpp
stack.cpp
stack.hpp
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
/*
 * A simple stack implementation (without templates)
 *
 * Description:
 *     A simple stack implementation that accepts integers as its datatype.
 *     Users are able to push to the back, pop from the back, and access the
 *     top element in the same way as they would with STL's stack.
 *
 * Author:
 *     Clara Nguyen
 */

#include <iostream>
#include "stack.hpp"

using namespace std;

//Node Struct
cn_stack::node::node() {
	next = prev = (node *)0x0;
}

//CN_Stack stuff
cn_stack::cn_stack() {
	//Make sentinel and make it point to itself
	sentinel = new node();
	sentinel->prev = sentinel->next = sentinel;

	N = 0;
}

cn_stack::~cn_stack() {
	clear();
	delete sentinel;
}

void cn_stack::clear() {
	while (N) {
		pop();
	}
}

void cn_stack::push(const int &i) {
	node *p = new node();
	p->data = i;
	
	//Get the top of the list.
	node *end = sentinel->prev;

	p->prev = sentinel->prev;
	p->next = sentinel;

	end->next = p;
	sentinel->prev = p;
	
	N++;
}

void cn_stack::pop() {
	node *p = sentinel->prev;
	sentinel->prev = p->prev;
	sentinel->prev->next = sentinel;
	delete p;
	N--;
}

int cn_stack::size() {
	return N;
}

int cn_stack::top() {
	return sentinel->prev->data;
}

void cn_stack::debug_print() {
	node *c = sentinel;
	cout << "Stack size: " << size() << endl;
	for (int i = 0; i < N; i++) {
		c = c->next;
		cout << c->data << endl;
	}
}