Hi everyone,
I have the implementation for a linked-list based Stack. I believe the entire code is correct, but only the way I call the push and pop function mighe be wrong. Any idea how they should be called? Mine returns garbage:
#include <iostream>
using namespace std;
typedef struct Elements {
struct Elements *next;
void *data;
} Elements;
bool push(Elements **Stack, void **data);
bool pop(Elements **Stack, void **data);
bool createStack(Elements **stack);
bool deleteStack(Elements **Stack);
int main()
{
Elements **myStack;
if (!createStack(myStack))
cout << "Something happend!" << endl;
cout << "Stack created." << endl;
int i = 10, j = 20, k;
if (push(myStack, (void**)&i))
cout << "Data added successfully!" << endl;
if (push(myStack, (void**)&j))
cout << "Data added successfully!" << endl;
if (pop(myStack, (void**)&k))
cout << "Data returned: " << k << endl;
}
bool createStack(Elements **Stack)
{
*Stack = NULL;
return true;
}
bool deleteStack(Elements **Stack)
{
Elements *next;
while (*Stack)
{
next = (*Stack) -> next;
delete *Stack;
*Stack = next;
}
return true;
}
bool push(Elements **Stack, void **data)
{
Elements *elem = new Elements;
if (!elem)
return false;
elem -> data = data;
elem -> next = *Stack;
*Stack = elem;
return true;
}
bool pop(Elements **Stack, void **data)
{
Elements *elem;
if (!(elem = *Stack))
return false;
*data = elem -> data;
*Stack = elem -> next;
delete elem;
return true;
}
Thank you.