Push node in Stack : Stacks in C++ – 1
February 12, 2011 Leave a comment
Here we will see how to perform basic operations on stacks (implemented here as a linked list) such as push, pop etc.
Question. Given a linked list implementation of a stack, write a function to push a node into the stack.
Let us assume that each node is of the following form:
typedef struct Node
struct Node* next;
Let us also assume that “*stack” denotes a pointer to the top element of the stack.
So we can proceed as follows:
// data is the data to be pushed into the stack.
// Function returns true if push succeeds; else, returns false.
bool push ( Node **stack, void *data)
Node *myNode = new Node;
if ( ! myNode) //memory allocation failed.
myNode -> data = data;
myNode -> next = *stack;
*stack = myNode;
We need to check whether dynamic memory was successfully allocated or not, since that may be a point of failure in the code.