facebook like button

31 July, 2011

program 70: stack with doubly linked list

The need:
    This program was written just to show how definitions of push() and pop() vary as the element structure is changed. This program also provide you a fully functional interactive console to do some operations on stack.
The code:
---------------------------------------------------
#include<stdio.h>
#include<stdlib.h>
// defining data-type node
struct linked_list
{
    int num;
    struct linked_list *next, *prev;
} ;
typedef struct linked_list node ;
//declaration of functions
node *push(node *top,int j);
int pop(node *top);
void display(node *top);
void rev_display(node *top);
main()
{
    int i,j;
    node *top=NULL ;
    while(1)
    {
      printf("\nEnter your choice :");
      printf("\n1. Push. Dont push 0");
      printf("\n2. Pop");
      printf("\n3. Display top to bottom");
      printf("\n4. Display bottom to top");
      printf("\n5. Exit\n");
     scanf("%d",&i);
        switch(i)
        {
            case 1 :
            scanf("%d",&j);
            top=push(top,j);
            break;
            case 2:
            j=pop(top);
            if(j)
            printf("Element popped is => %d\n",j);
            break;
            case 3:
            display(top);
            break;
            case 4:
            printf("Elements in the stack (bottom to top) are :\n");
            rev_display(top);
            break;
            case 5:
            exit(0);
            default:
            printf("Invalid choice !!!\n\n");
        }
    }
}
/*Inserting the elements using push function*/
node *push(node *top,int j)
{
  node *m;
  m=(node *)malloc(sizeof(node));
  m->num=j;
  m->next=top;
  m->prev=NULL;
  if(top)
  top->prev=m;
  return(m);
}
/*Removing the elements using pop function*/
int pop(node *top)
{
int j;
node *temp=top;
  if(temp==NULL)
  {
    printf("\nSTACK is Empty!!!\n");
  }
  else
  {
  j=top->num;
  temp=top->next;
  temp->prev=NULL;
  free(top);
  top=temp;
    return (j);
  }
return 0;
}
/*Displaying the elements */
void display(node *top)
{
  node *pointer=NULL;
  int j=0;
  pointer=top;
  if(top)
  {
  printf("Elements in the stack (top to bottom) are :\n");
  while(pointer!=NULL)
  {
    printf("%d-->",pointer->num);
    pointer=pointer->next;
    j++;
    if(j>20)
    break;
  }
  printf("END\n\n");
 }
else
printf("Stack is empty !!!\n");
}
void rev_display(node *top)
{
  node *p1=NULL,*p2=NULL;
  p1=top;
  while(p1!=NULL)
  {
  p2=p1;
    p1=p1->next;
  }
    while(p2!=NULL)
  {
    printf("%d-->",p2->num);
    p2=p2->prev;
  }
  printf("END\n\n");
}
-----------------------------------------------------

No comments:

Post a Comment

feel free to ask your doubts... if any
you can post your doubts on
www.facebook.com/programsimply