Home / utk / cs140 / sp19 / live_codings_in_lab / part1_concepts / stack_templated / stack.hpp
Directory Listing
main.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
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
127
/*
 * A simple stack implementation (with templates)
 *
 * Description:
 *     Aims to implement a simple stack that users are able to push to, as well
 *     as pop from. They are able to access the top of the stack in the same
 *     way as STL's Stack as well.
 *
 * Author:
 *     Clara Nguyen
 */

#ifndef __STACK__
#define __STACK__

#include <iostream>
using namespace std;

//Prototype
template <typename T>
class cn_stack {
	public:
		struct node {
			T     data;
			node *next,
			     *prev;

			node();
		};

	public:
		cn_stack();
		~cn_stack();

		void clear();

		void push(const T&);
		void pop();

		int size();

		const T& top();

		void debug_print();

	private:
		node *sentinel;
		int N;
};

//Definitions
//Node Struct
template <typename T>
cn_stack<T>::node::node() {
	next = prev = (node *)0x0;
}

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

	N = 0;
}

template <typename T>
cn_stack<T>::~cn_stack() {
	clear();
	delete sentinel;
}

template <typename T>
void cn_stack<T>::clear() {
	while (N) {
		pop();
	}
}

template <typename T>
void cn_stack<T>::push(const T &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++;
}

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

template <typename T>
int cn_stack<T>::size() {
	return N;
}

template <typename T>
const T& cn_stack<T>::top() {
	return sentinel->prev->data;
}

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

#endif