Stack implementation using linked list in c

1:  #include <stdio.h>  
2:  #include <stdlib.h>  
3:  #include <malloc.h>  
4:  #include <dos.h>  
5:  struct stack  
6:  {  
7:       int data;  
8:       struct stack*next;  
9:  };  
10:  typedef struct stack STACK;  
11:  STACK*top=NULL;  
12:  void push()  
13:  {  
14:   STACK*temp;       
15:   if(top==NULL)       
16:   {  
17:        top=(STACK*)malloc(sizeof(STACK));  
18:        printf("\nEnter data: ");  
19:        scanf("%d",&top->data);  
20:        top->next=NULL;  
21:        return;  
22:   }  
23:   temp=(STACK*)malloc(sizeof(STACK));  
24:   printf("\nEnter data: ");  
25:   scanf("%d",&temp->data);  
26:   temp->next=top;  
27:   top=temp;  
28:   return;   
29:  }  
30:  void pop()  
31:  {  
32:       STACK*temp;  
33:    if(top==NULL)       
34:    {  
35:         printf("stack is underflow\n");  
36:         system("PAUSE");  
37:         return;  
38:    }  
39:    printf("pop element is:%d\n",top->data);  
40:    temp=top;  
41:    top=top->next;  
42:    temp->next=NULL;  
43:    free(temp);  
44:    system("PAUSE");  
45:    return;  
46:  }  
47:  void peek()  
48:  {  
49:       STACK*temp;  
50:       if(top==NULL)  
51:       {  
52:            printf("stack is empty\n");  
53:            system("PAUSE");  
54:            return;  
55:       }  
56:       printf("stack elements: ");  
57:       temp=top;  
58:       do  
59:       {  
60:            printf("%d ",temp->data);  
61:            temp=temp->next;  
62:       }while(temp!=NULL);  
63:       system("PAUSE");  
64:       return;       
65:  }  
66:  int main(void)  
67:  {  
68:       int option;  
69:       while(1)  
70:       {  
71:            system("CLS");  
72:            printf("\nPUSH PRESS 1: ");  
73:            printf("\nPOP PRESS 2: ");  
74:            printf("\nPEEK PRESS 3: ");  
75:            printf("\nEXIT PRESS 4: ");  
76:            scanf("%d",&option);  
77:            switch(option)  
78:            {  
79:                 case 1: push();  
80:                           break;  
81:                 case 2: pop();  
82:                           break;  
83:                 case 3: peek();  
84:                           break;                 
85:                 case 4: free(top);  
86:                     return EXIT_SUCCESS;  
87:                 default: printf("INVALID OPTION\n");  
88:                            system("PAUSE");  
89:            }  
90:       }  
91:  }  

0 comments:

Post a Comment