User Tools

Site Tools


user:dblanch1:portfolio:dataproject4

Stack Demo Programme

The purpose of this programme was to gain familiarity with the basic nature of a stack. We explored this by retrieving characters from stdin, storing them in our stack (one character per node), then popping them out of our stack and displaying the character. The output would be the reverse of the input (thanks to the last in, first out nature of the stack).

A clip of it running:

doug@slackware:~/src/stack_demo$ ./stack_demo 
abcdef

fedcba

The command to compile this programme, with the source provided beneath it, is as follows:

g++ -o stack_demo stack_demo.cpp -g

include/ltnodes.hpp

#ifndef _LTNODES
#define _LTNODES
#include <cstddef>

template <class T> struct SNode{
	public:
		T data;
		SNode* next;
		
		SNode(){
			next = NULL;
		}
		
		SNode(T d){
			data = d;
			next = NULL;
		}
};

template <class T> struct DNode{
	public:
		T data;
		DNode *next, *prev;
		
		DNode(){
			next = NULL;
			prev = NULL;
		}
		
		DNode(T d){
			data = d;
			next = NULL;
			prev = NULL;
		}
};

#endif

include/ltstack.hpp

#ifndef _LTSTACK
#define _LTSTACK
#include <cstddef>
#include "ltnodes.hpp"

template <class T> class Stack{
	private:
		SNode<T> *head;
		unsigned long long size, capacity;
		
	public:
		Stack(bool d = false, unsigned long long c = 0){
			head = NULL;
			size = 0;
			capacity = c;
		}
	
		unsigned long long get_size(){
			return size;
		}
		
		unsigned long long get_capacity(){
			return capacity;
		}
		
		void set_capacity(unsigned long long c){
			capacity = c;
		}
	
		SNode<T> *peek(){
			return this->head;
		}
		
		SNode<T> *pop(){
			SNode<T>* curr = head;
			if (head != NULL){
				head = head->next;
				curr->next = NULL;
			}
			size--;
			return curr;
		}
		
		bool push(SNode<T>* node){
			if (size < capacity || capacity == 0){
				node->next = head;
				head = node;
				size++;
				return true;
			}
			return false;
		}
};

#endif

src/stack_demo.cpp

#include <iostream>
#include <cstdio>
#include "../include/ltstack.hpp"

int main(){
	Stack<char> stack;
	SNode<char>* curr = new SNode<char>;
	char tmp = 'a';
	
	while(tmp != '\n'){
		tmp = fgetc(stdin);
		curr->data = tmp;
		stack.push(curr);
		if (tmp != '\n'){
			curr = new SNode<char>;
		}
	}
	
	if (stack.peek() != NULL){
		curr = stack.pop();
		while (curr != NULL){
			std::cout << curr->data;
			delete curr;
			curr = stack.pop();
		}
	}	
	return false;
}
user/dblanch1/portfolio/dataproject4.txt · Last modified: 2013/11/21 08:31 by dblanch1