Skip to content

Instantly share code, notes, and snippets.

@SergiyOsadchyy
Created February 23, 2017 06:45
Show Gist options
  • Save SergiyOsadchyy/caca661bc4599e833d72169a5b34c749 to your computer and use it in GitHub Desktop.
Save SergiyOsadchyy/caca661bc4599e833d72169a5b34c749 to your computer and use it in GitHub Desktop.
Stack_Class
// Stack.h
// Stack_Class
//
// Created by Sergiy on 23.02.17.
#ifndef Stack_h
#define Stack_h
#include <iostream>
#include <string>
#include <string.h>
using namespace std;
class Stack
{
private:
struct item
{
string name;
int value;
item* prev;
};
item* stackPtr;
public:
void push( string name, int value );
void pop( );
void readItem( item* r);
void print( );
Stack();
~Stack();
};
#endif /* Stack_h */
//----------------------------
// Stack.cpp
// Stack_Class
//
// Created by Sergiy on 23.02.17.
#include <stdio.h>
#include <cstdlib>
#include <iostream>
#include "Stack.h"
using namespace std;
Stack::Stack()
{
stackPtr = NULL;
}
Stack::~Stack()
{
item* p1;
item* p2;
p1 = stackPtr;
while ( p1 != NULL )
{
p2 = p1;
p1 = p1->prev;
p2->prev = NULL;
delete p2;
}
}
void Stack::push( string name, int value )
{
item* n = new item;
n->name = name;
n->value = value;
if ( stackPtr == NULL )
{
stackPtr = n;
stackPtr->prev = NULL;
}
else
{
n->prev = stackPtr;
stackPtr = n;
}
}
void Stack::readItem( item *r )
{
cout << "\n----------------" << endl;
cout << "name: " << r->name << endl;
cout << "value " << r->value << endl;
cout << "----------------" << endl;
}
void Stack::pop( )
{
if (stackPtr == NULL)
{
cout << "\nThere is nothing on the stack" << endl;
}
else
{
item* p = stackPtr;
readItem(p);
stackPtr = stackPtr->prev;
p->prev = NULL;
delete p;
}
}
void Stack::print( )
{
item* p = stackPtr;
while ( p != NULL)
{
readItem(p);
p = p->prev;
}
}
//-------------------------
// main.cpp
// Stack_Class
//
// Created by Sergiy on 23.02.17.
#include <iostream>
#include <string>
#include <string.h>
#include <cstdlib>
#include "Stack.h"
using namespace std;
int main(int argc, const char * argv[])
{
Stack Sergio;
Sergio.push("Sergio", 3);
Sergio.push("Coffe", 0);
Sergio.push("Lunch", 0);
Sergio.push("Videos", 5);
Sergio.print();
cout << "Popping...\n";
Sergio.pop();
cout << "Popping...\n";
Sergio.pop();
cout << "Popping...\n";
Sergio.pop();
cout << "Popping...\n";
Sergio.pop();
cout << "Popping...\n";
Sergio.pop();
cout << "\n\n New stack\n";
Sergio.push("Books", 100);
Sergio.push("Pencil", 1);
Sergio.print();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment