About Stack

A stack is a linear data structure which allows any kind of operations on only top of the stack. Stack follows particular order only i.e LIFO(Last In First Out) or FILO(First In Last Out).

About Linked list

linked list is a way to store a collection of elements. Like an array, these can be character or integers. Each element in a linked list is stored in the form of a node.

Declaring a Stack

In C language, a stack list can be implemented using structure and pointers, it’s simpler to single linked list.

struct STACK
{
  int data;
  struct STACK*next;
};
struct STACK*top=NULL;
typedef struct STACK stack;

Stack Push Operation

Push, Its a simple process to insert or add a new element to stack using linked list add node approach.

void push()
{
  stack*ttop;
  int data;
  if(top==NULL)
  {
    top=(stack*)malloc(sizeof(stack));
    printf("\nEnter data: ");
    scanf("%d",&data);
    //scanf("%d",&top->data);
    top->data=data;
    top->next=NULL;
    return;
  }
  else
  {
    ttop=(stack*)malloc(sizeof(stack));
    printf("\nEnter Data: ");
    scanf("%d",&data);
    ttop->data=data;
    ttop->next=top;
    top=ttop;
    return;
  }
}

Stack Pop Operation

Pop, It’s a simple process to delete or remove a new element to stack using linked list delete node approach.

void pop()
{
  stack*ttop;
  if(top==NULL)
  {
   printf("\nSTACK UNDERFLOW(EMPTY): ");
   return;
  }
  else
  {
   ttop=top;
   top=top->next;
   ttop->next=NULL;
   printf("\ndeleted data:%d",ttop->data);
   free(ttop);
   return;
  }
}

Stack Peek Operation

Peek, It’s a simple process to display or traversal operation on Stack without deleting an element 

void peek()
{
  stack*ttop;
  if(top==NULL)
  {
   printf("\nSTACK IS EMPTY");
   return;
  }
  printf("\nSTACK DATA: ");
  ttop=top;
  do
  {
   printf("%d ",ttop->data);
   ttop=ttop->next;
  }while(ttop!=NULL);
  return;
}

main() function Implementation 

int main()
{
  int option;
  while(1)
  {
   clrscr();
   printf("\n1.FOR PUSH : ");
   printf("\n2.FOR POP  : ");
   printf("\n3.FOR PEEK : ");
   printf("\n4.FOR EXIT : ");
   scanf("%d",&option);
   switch(option)
   {
    case 1: push();
          break;
    case 2: pop();
          break;
    case 3: peek();
          break;
    case 4: free(top);
          top=NULL;
          return 0;

    default: printf("\nInvalid Option: ");
   }
    }
    return 0;
}

 

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *