Create Stack in C++ with Push, Pop etc - c++

We are trying to create a C++ program that works like a stack.
The following instructions are given:
There should be several methods:
We have to use this definition of the StackElement:
struct StackElement {
int digit;
StackElement* predecessor;
};
The problem now is how to create the push-function without an next parameter as there was with ordinary lists. The same for the pop function.
We accomplished to get push() create a new StackElement and pop() delete the new Element, but with 2 new Elements, those methods aren't working properly.
Global parameter stack0:
StackElement *stack0 = new StackElement;
This is the code for the push-function:
StackElement push(int z){
StackElement *stack1 = new StackElement;
stack1->digit = z;
stack1->predecessor = NULL;
stack0->predecessor = stack1;
stack1 = stack0;
This is the pop() method:
void pop(){
StackElement *stack1 = new StackElement;
if (stack0!=NULL){
stack1->digit = 0;
stack0->predecessor = NULL; //predecessor = NULL;
}
}
And finally the main method:
int main()
{
int z;
create();
cout << "Which number to the stack?" << endl;
cin >> z;
push(z);
pop();
print();
return 0;
}
We thought about creating a new StackElement, that would work as a 'pseudo'-StackElement and would always stay on top so that the 'real' element on the top would always be the predecessor of the pseudo-Element - but we think this would be against how the stack should work.
So do you guys have any clues on how to proceed? Is there something we are just missing?

1st) Why not using std::stack?
2nd) Stack should be LIFO. That means your stack0 should always be the newest one... This leads to:
StackElement* stack0 = NULL; // until C++11
// StackElement* stack0 = nullptr; // since C++11
void push(int z) {
StackElement *stack1 = new StackElement;
stack1->digit = z;
stack1->predecessor = stack0;
stack0 = stack1;
}
void pop() {
if(stack0) {
StackElement *tmp = stack0;
stack0 = stack0->predecessor;
delete tmp;
}
}
You don't need the allocate a new one in the pop function. This will end in a huge memory leak.
What you meant by pseudo is called root element and is sometimes used in sequences. But not necessary here, since stack0 is the root or in this case the end (the first element and the end).
A better approach would be to encapsulate it in a class as ryrich mentioned in his answer. And the best approach would be using the C++-given std::stack.

You're on the right track here. To keep track of your elements, you need a class. Something like:
class Stack{
private:
StackElement *last_data, *first_data;
public:
Stack():last_data(NULL), first_data(NULL){}
void push(int digit);
void pop();
};
Have the push/pop functions part of the Stack class. For example, push:
void Stack::push(int digit)
{
StackElement *p=new StackElement();
p->digit = digit;
if(last_data)
p->predecessor=last_data;
else // empty stack
{
p->predecessor=NULL;
first_data = p;
}
last_data=p;
}
Hope this helps.
Edit: I'll add pop function for completeness:
void Stack::pop()
{
if (last_data)
{
StackElement *tp = last_data;
last_data = last_data->predecessor;
delete tp;
}
}

if the stack is full and we try to put something in it then it will give us the error of stack overflow
void IntStack::push()
{
clrscr();
int num;
if(top>=stackSize)
cout<<"stack Overflow"<<endl;
else
{
cout<<"Enter Number=";
cin>>num;
top++;
stackArray[top]=num;
}
}

Related

Stack (Data structure) implementation

So I'm just starting to learn about data structures through a course on Coursera and I learned that it's possible to create a stack data structure by using an array. I was just wondering if what I have written is what a stack is supposed to do.
#include <iostream>
using namespace std;
const int MAX_SIZE = 10000;
class Stack {
public:
Stack();
~Stack();
void push(int n);
void pop();
int top();
bool isEmpty() const;
void print() const;
private:
int* array [MAX_SIZE];
int curNum;
};
Stack::Stack() {
curNum = 0;
}
Stack::~Stack() {
for (int i = 0; i < curNum; ++i)
delete array[i];
}
void Stack::push(int n) {
if (curNum >= MAX_SIZE) {
cout << "reached maximum capacity...can't add an element\n";
return;
}
array[curNum] = new int(n);
curNum++;
}
void Stack::pop() {
delete array[curNum];
curNum--;
}
int Stack::top() {
return *array[curNum];
}
void Stack::print() const{
for (int i = 0; i < curNum; ++i)
cout << *array[i] << endl;
}
bool Stack::isEmpty() const{
return curNum == 0;
}
int main () {
Stack stack;
stack.push(5);
stack.print();
stack.pop();
}
Also, I see that a lot of people don't use dynamic memory allocation for this kind of task. Is there a reason why? It seems like specifying a size for the array at compile time might lead to insufficient memory or over-allocating memory to me
Yes, this is one way to implement a stack. The important thing that defines a stack is LIFO (last in, first out). So as long as you are only adding to and removing from the top, then that is a stack. Think of it as a stack of dishes; if 10 dishes are put one by one into a stack, and then one by one removed from said stack, the first dish put on will also be the last dish removed. You can't remove a dish that's not at the top, as it is covered by all the dishes above it. The same is true with a stack data structure.
So your implementation is indeed a stack.
The stack we use when we want something in reverse order and stack also takes constant time means O(1) time to push and pop means to remove or to add it will work much faster

C++ pointer linked list

So I am new to c++ sorry if this is not to clear.
I have a class:
class Item
{
int noItem;
int qItem;
public:
Item(int noItem, int qItem)
{
this->noItem = noItem;
this->qItem = qItem;
}
int getNoItem()
{
return noItem;
}
int getQntItem()
{
return qItem;
}
};
Then the following class:
class Element
{
public:
Element()
{
data = NULL;
}
//to set and access data hold in node
void setElement(Item *data)
{
this->data = data;
}
Item* getElement(void)
{
return(data);
}
private:
Item *data;
};
This one also:
class ListeChainee
{
public:
ListeChainee()
{
courant = NULL;
}
void ajoutListe(Item *data)
{
Element *newData;
//set data
newData->setElement(data);
//check if list is empty
if( courant == NULL)
{
//set current pointer
courant = newData;
}
}
//get data from element pointed at by current pointer
Item* elementCourant(void)
{
if(courant != NULL)
{
return courant->getElement();
}
else
{
return NULL;
}
}
private:
//data members
Element *courant; //pointer to current element in list
};
The code is missing some stuff for other things, but my problem is this:
int main(int argc, char* argv[])
{
ListeChainee listeCH;
Item i1(123,456);
listeCH.ajoutListe(&i1);
cout << listeCH.elementCourant()->getNoItem();
system("pause");
return 0;
}
I expect 123 to be outputted, but I see some other number. Not sure why.
Thanks.
Your Element *newData doesn't have an instance of Element class, so it will crash when you try to access the instance pointed by newData.
Try to change Element *newData; to Element *newData = new Element;.
ps.: Don't forget to delete it when you don't need the instance any more.
This method is writing to uninitialized memory:
void ajoutListe(Item *data)
{
Element *new;
//set data
new->setElement(data); // Right here, "new" is an uninitialized pointer
//check if list is empty
if( courant == NULL)
{
//set current pointer
courant = new;
}
}
I'm surprised this compiles (does it?). This code should also crash.
The strange number you're getting is surely some random part of memory. You may want to think more about memory management -- there are numerous problems here. When ajoutListe is called, why does the courant member only get set if it's NULL? Do we just leak the new Element? How do we actually traverse this list?

Implementation of stack in C++ without using <stack>

I want to make an implementation of stack, I found a working model on the internet, unfortunately it is based on the idea that I know the size of the stack I want to implement right away. What I want to do is be able to add segments to my stack as they are needed, because potential maximum amount of the slots required goes into 10s of thousands and from my understanding making the size set in stone (when all of it is not needed most of the time) is a huge waste of memory and loss of the execution speed of the program. I also do not want to use any complex prewritten functions in my implementation (the functions provided by STL or different libraries such as vector etc.) as I want to understand all of them more by trying to make them myself/with brief help.
struct variabl {
char *given_name;
double value;
};
variabl* variables[50000];
int c = 0;
int end_of_stack = 0;
class Stack
{
private:
int top, length;
char *z;
int index_struc = 0;
public:
Stack(int = 0);
~Stack();
char pop();
void push();
};
Stack::Stack(int size) /*
This is where the problem begins, I want to be able to allocate the size
dynamically.
*/
{
top = -1;
length = size;
z = new char[length];
}
void Stack::push()
{
++top;
z[top] = variables[index_struc]->value;
index_struc++;
}
char Stack::pop()
{
end_of_stack = 0;
if (z == 0 || top == -1)
{
end_of_stack = 1;
return NULL;
}
char top_stack = z[top];
top--;
length--;
return top_stack;
}
Stack::~Stack()
{
delete[] z;
}
I had somewhat of a idea, and tried doing
Stack stackk
//whenever I want to put another thing into stack
stackk.push = new char;
but then I didnt completely understand how will it work for my purpose, I don't think it will be fully accessible with the pop method etc because it will be a set of separate arrays/variables right? I want the implementation to remain reasonably simple so I can understand it.
Change your push function to take a parameter, rather than needing to reference variables.
To handle pushes, start with an initial length of your array z (and change z to a better variable name). When you are pushing a new value, check if the new value will mean that the size of your array is too small (by comparing length and top). If it will exceed the current size, allocate a bigger array and copy the values from z to the new array, free up z, and make z point to the new array.
Here you have a simple implementation without the need of reallocating arrays. It uses the auxiliary class Node, that holds a value, and a pointer to another Node (that is set to NULL to indicate the end of the stack).
main() tests the stack by reading commands of the form
p c: push c to the stack
g: print top of stack and pop
#include <cstdlib>
#include <iostream>
using namespace std;
class Node {
private:
char c;
Node *next;
public:
Node(char cc, Node *nnext){
c = cc;
next = nnext;
}
char getChar(){
return c;
}
Node *getNext(){
return next;
}
~Node(){}
};
class Stack {
private:
Node *start;
public:
Stack(){
start = NULL;
}
void push(char c){
start = new Node(c, start);
}
char pop(){
if(start == NULL){
//Handle error
cerr << "pop on empty stack" << endl;
exit(1);
}
else {
char r = (*start).getChar();
Node* newstart = (*start).getNext();
delete start;
start = newstart;
return r;
}
}
bool empty(){
return start == NULL;
}
};
int main(){
char c, k;
Stack st;
while(cin>>c){
switch(c){
case 'p':
cin >> k;
st.push(k);
break;
case 'g':
cout << st.pop()<<endl;
break;
}
}
return 0;
}

Trie Implementation in C++

I am trying to implement the trie as shown on the TopCoder page. I am modifying it a bit to store the phone numbers of the users. I am getting segmentation fault. Can some one please point out the error.
#include<iostream>
#include<stdlib.h>
using namespace std;
struct node{
int words;
int prefix;
long phone;
struct node* children[26];
};
struct node* initialize(struct node* root) {
root = new (struct node);
for(int i=0;i<26;i++){
root->children[i] = NULL;
}
root->word = 0;
root->prefix = 0;
return root;
}
int getIndex(char l) {
if(l>='A' && l<='Z'){
return l-'A';
}else if(l>='a' && l<='z'){
return l-'a';
}
}
void add(struct node* root, char * name, int data) {
if(*(name)== '\0') {
root->words = root->words+1;
root->phone = data;
} else {
root->prefix = root->prefix + 1;
char ch = *name;
int index = getIndex(ch);
if(root->children[ch]==NULL) {
struct node* temp = NULL;
root->children[ch] = initialize(temp);
}
add(root->children[ch],name++, data);
}
}
int main(){
struct node* root = NULL;
root = initialize(root);
add(root,(char *)"test",1111111111);
add(root,(char *)"teser",2222222222);
cout<<root->prefix<<endl;
return 0;
}
Added a new function after making suggested changes:
void getPhone(struct node* root, char* name){
while(*(name) != '\0' || root!=NULL) {
char ch = *name;
int index = getIndex(ch);
root = root->children[ch];
++name;
}
if(*(name) == '\0'){
cout<<root->phone<<endl;
}
}
Change this:
add(root->children[ch], name++, data);
// ---------------------^^^^^^
To this:
add(root->children[ch], ++name, data);
// ---------------------^^^^^^
The remainder of the issues in this code I leave to you, but that is the cause of your run up call-stack.
EDIT OP ask for further analysis, and while I normally don't do so, this was a fairly simple application on which to expand.
This is done in several places:
int index = getIndex(ch);
root = root->children[ch];
... etc. continue using ch instead of index
It begs the question: "Why did we just ask for an index that we promptly ignore and use the char anyway?" This is done in add() and getPhone(). You should use index after computing it for all peeks inside children[] arrays.
Also, the initialize() function needs to be either revamped or outright thrown out in favor of a constructor-based solution, where that code truly belongs. Finally, if this trie is supposed to be tracking usage counts of words generated and prefixes each level is participating in, I'm not clear why you need both words and prefix counters, but in either case to update the counters your recursive decent in add() should bump them up on the back-recurse.

Memory leak in trivial stack implementation

I'm decently experienced with Python and Java, but I recently decided to learn C++. I decided to make a quick integer stack implementation, but it has a massive memory leak that I can't understand. When I pop the node, it doesn't seem to be releasing the memory even though I explicitly delete the old node upon poping it. When I run it, it uses 150mb of memory, but doesn't release any of it after I empty the stack. I would appreciate any help since this is my first foray into a language without garbage collection. This was compiled with gcc 4.3 on 64-bit Kubuntu.
//a trivial linked list based stack of integers
#include <iostream>
using namespace std;
class Node
{
private:
int num;
Node * next;
public:
Node(int data, Node * next);
int getData();
Node * getNext();
};
Node::Node(int data, Node * next_node)
{
num = data;
next = next_node;
}
inline int Node::getData()
{
return num;
}
inline Node* Node::getNext()
{
return next;
}
class Stack
{
private:
unsigned long int n;
Node * top;
public:
Stack(int first);
Stack();
void push(int data);
int pop();
int peek();
unsigned long int getSize();
void print();
void empty();
};
Stack::Stack(int first)
{
Node first_top (first, NULL);
top = &first_top;
n = 1;
}
Stack::Stack()
{
top = NULL;
n = 0;
}
void Stack::push(int data)
{
Node* old_top = top;
Node* new_top = new Node(data,old_top);
top = new_top;
n++;
}
int Stack::pop()
{
Node* old_top = top;
int ret_num = old_top->getData();
top = old_top->getNext();
delete old_top;
n--;
return ret_num;
}
inline int Stack::peek()
{
return top->getData();
}
inline unsigned long int Stack::getSize()
{
return n;
}
void Stack::print()
{
Node* current = top;
cout << "Stack: [";
for(unsigned long int i = 0; i<n-1; i++)
{
cout << current->getData() << ", ";
current = current->getNext();
}
cout << current->getData() << "]" << endl;
}
void Stack::empty()
{
unsigned long int upper = n;
for(unsigned long int i = 0; i<upper; i++)
{
this->pop();
}
}
Stack createStackRange(int start, int end, int step = 1)
{
Stack stack = Stack();
for(int i = start; i <= end; i+=step)
{
stack.push(i);
}
return stack;
}
int main()
{
Stack s = createStackRange(0,5e6);
cout << s.peek() << endl;
sleep(1);
cout << "emptying" <<endl;
s.empty();
cout << "emptied" <<endl;
cout << "The size of the stack is " << s.getSize()<<endl;
cout << "waiting..." << endl;
sleep(10);
return 0;
}
How do you KNOW the memory isn't being released? The runtime library will manage allocations and may not release the memory back to the OS until the program terminates. If that's the case, the memory will be available for other allocations within your program during its execution.
However.... you seem to have other problems. My C++ is really rusty since I've been doing Java for 15 years, but in your Stack::Stack constructor you're allocating a Node instance on the system stack and then storing a reference to it in your "Stack". That Node instance goes out of scope when the constructor ends, leaving a dangling pointer.
Stack::Stack(int first)
{
Node first_top (first, NULL);
top = &first_top;
n = 1;
}
This is wrong , you cant assign address of a local object to class member( top ) , since local objects get destroyed when function returns.
Create a node on heap rather than stack , do something like this :
Stack::Stack(int first)
{
top = new Node(first, NULL);
n = 1;
}
And Make the concept of link list clear and use pen and paper if you can do so.
Your Stack::Push(int) operation seems buggy check it out what you have forget to do.
My suggestion is try to implement generic stack with the help of template ,so it will work for all data type .
When createStackRange() returns it'll return a copy of the Stack using the compiler-generated copy constructor which just makes a bitwise copy (i.e., it'll copy the pointer to the first node and the size.)
More seriously, you're missing the destructor for the Stack class. Ideally you'd have it walk the list and call delete on each Node. The Stack object created on the processor stack will automatically be cleaned up automatically when main() exits, but without a destructor, the nodes will still be allocated when the program ends. You probably want something like this for it:
Stack::~Stack()
{
while ( top )
{
Next *next = top->getNext();
delete top;
top = next;
}
}
The way to think of it is that the C++ compiler will automatically generate copy constructors and destructors for you, but they're normally shallow. If you need deep behavior you've got to do it implement it yourself somewhere.
After poring over the code, I couldn't find the leak so I compiled it and ran it in a debugger myself. I agree with Jim Garrision - I think you're seeing an artifact of the runtime rather than an actual leak, because I'm not seeing it on my side. The issues pointed out by NickLarsen and smith are both actual issues that you want to correct, but if you trace the code through, neither should actually be causing the problem you describe. The code smith singles out is never called in your example, and the code Nick singles out would cause other issues, but not the one you're seeing.
Creat a stub to test your code and user Memory Analysis tool like "Valgrind". This will find out memory leaks and corruptions for you.
check man-pages for more information.
Note that you should only roll your own stack for educational purposes. For any real code, you should use the stack implementation that comes with the C++ standard library...