Coders Packet

C program for implementation of a Stack using Linked List

By Srishti Dhaval Patkar

This is a C program that implements the stack operations using a linked list. The program includes stack operations like push operation, pop operation, Display and Quit option.

Implementation of STACK using a LINKED LIST

This is a C program that implements the stack operations using a linked list.

Declaration of data type struct node:

struct node
{
  int data;
  struct node *link;
}*top=NULL;

 

The stack operations in the given program are:

1) Push: 

To insert an element to the stack. In a stack, a new element is always added from the top of the stack. 

Given below is the function used in the code for push operation. 

We declare a pointer to node i.e. newnode and allocate memory from heap using malloc function. We take input for the data part of newnode from the user. We update the link of newnode to top and make newnode the new top.

void push(int x)
{
  struct node *newnode;
  newnode=(struct node *)malloc(sizeof(struct node));
  newnode->data=x;
newnode->link=top; top=newnode; }

 

2) Pop: 

To delete an element from the stack. In a stack, an element is always deleted from the top of the stack. 

Given below is the function used in the code for the pop operation. 

First, we check if the stack is empty. If not, we take a pointer temp equal to the top. We change the top to the link of top and free temp.

void pop()
{
  struct node *temp;
  temp=top;	
  if(top==NULL)
  {
    printf("Stack underflow\n");
  }
  else
  {
    top=top->link;
    free(temp);
  }
}

 

3) Display:

To display the elements in the stack.

Given below is the function to display the elements of the stack.

void display()
{
  if(top==NULL)
  {
    printf("Stack Empty\n");	
  }	
  else
  {
    for(struct node *temp=top;temp!=NULL;temp=temp->link)
    {
      printf("%d ",temp->data);
    }
  }
}

 

Download Complete Code

Comments

No comments yet