Push node in Stack : Stacks in C++ – 1

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.

Solution.

Let us assume that each node is of the following form:

typedef struct Node

{

struct Node* next;

void *data;

} Node;

——

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.

return false;

myNode -> data = data;

myNode -> next = *stack;

*stack = myNode;

return true;

}

—–

We need to check whether dynamic memory was successfully allocated or not, since that may be a point of failure in the code.

—–

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: