Computer Concept & Programming In C - Unit IV - 15

Q.28 Implement Stack using Linked List.                (AKTU. 2009-10)
Related Questions -
Q. Give an algorithm for push and pop operations on stack. Also write a program in C language to create a stack of even numbers.                                    (AKTU. 2012-13)
Ans.
#include<stdio.h>
#include<conio.h>
#include<malloc.h>

/*structure of single stack node*/
struct node{
  int info;
  struct node *next;
};

struct node *top_of_stack, *temp, *new_node;

/* To allocate memory for a node*/
struct node* create_node(void);

/* loop control*/
int flag = 0;

/*Elementry stack functions are :*/
/* 1)Insertion at the TOP OF STACK (PUSH) */
 void push(void);

/* 2)Deletion at TOP OF STACK (POP)*/
 void pop(void);

/* 3)Traverse the stack*/
 void traverse(void);

/* 4)Main - Menu to access all the above functions*/
void main_menu(void);

void main()
{
 clrscr();
 top_of_stack = NULL;
 printf("\n\t\tIMPLEMENTATION OF STACK BY LINKED LIST ");
 printf("\n\t\tCreated by ABHINAV SHALABH KULSHRESTHA");
 printf("\n\n");
 while(1)
 {
   main_menu();
   if(flag == 1)
     break;
  }
}
void main_menu(void)
{
  int ch;
  char c;
  printf("\nMAIN-MENU");
  printf("\nPress 0. To PUSH.\n");
  printf("\nPress 1. To POP.\n");
  printf("\nPress 2. To TRAVERSE.\n");
  printf("\nPress any other key to exit.\n");
  printf("\nEnter your choice.\n");
  c = NULL;
  c = getche();
  ch = c - '0';
  switch(ch)
  {
    case 0: push();
   traverse();
    break;

    case 1: pop();
   traverse();
    break;

    case 2: traverse();
    break;

     default: flag = 1;
    break;
}/* end switch case*/
}/* end main_menu  */

void push(void)
{
  int num;
  printf("\nInsert at top of stack (PUSH)");
  printf("\nEnter the number.\n ");
  scanf("%d", &num);
  new_node = create_node();
  new_node -> info = num;
  new_node -> next = NULL;
  if(top_of_stack == NULL)
    top_of_stack = new_node;
  else
  {
    new_node -> next = top_of_stack;
    top_of_stack = new_node;
  }
}

void pop(void)
{
 printf("\nDelete at top of stack (POP)");
 temp = top_of_stack;
 top_of_stack = temp -> next;
 free(temp);
}

void traverse(void)
{
 printf("\nCurrent status of stack : \n");
 temp = top_of_stack;
 printf("\nTop Of Stack*-->");
 if(top_of_stack != NULL)
 {
   while(temp -> next != NULL)
     {
       printf("%d-->",temp ->info);
       temp = temp ->next;
     }
   printf("%d",temp ->info);
   printf("||*\n");
  }
  else
  {
    printf("stack is Empty");
    printf("||*\n");
  }
}

struct node* create_node(void)
{
 struct node *tmp = NULL;
 tmp =(struct node*)( malloc(sizeof(struct node)));
 if(tmp != NULL)
  return tmp;
 else
 {
  printf("\nMemory is not Free.Press any key to continue");
  getch();
  return NULL;
 }
}