Advertisement
Guest User

stack implementation in c using a linked list

a guest
Jun 17th, 2011
1,634
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.10 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct Element{
  5.     int *data;
  6.     struct Element *next;
  7. }Element;  
  8.  
  9. int push(Element **stack,int *data);
  10.  
  11. int pop(Element **stack,int **data);
  12.  
  13. int createStack(Element **stack);
  14.  
  15. int deleteStack(Element **stack);
  16.  
  17. ////////////////////////////
  18.  
  19. int createStack(Element **stack){
  20.     *stack=NULL;
  21.     return 0;
  22. }
  23.  
  24. int push(Element **stack,int *data){
  25.     Element *elem;
  26.     elem=(Element*)malloc(sizeof(Element*));
  27.     if (!elem) return 1;
  28.    
  29.     elem->data=data;
  30.     elem->next=*stack;
  31.     *stack=elem;
  32.     return 0;
  33. }
  34.  
  35. int pop(Element **stack,int **data){
  36.     Element *elem;
  37.     elem=*stack;
  38.     if (!elem) return 1;
  39.    
  40.     *stack=elem->next;
  41.     *data=(elem->data);
  42.     free(elem);
  43.     return 0;
  44. }
  45.  
  46. int deleteStack(Element **stack){
  47.     Element *next;
  48.    
  49.     while(*stack){
  50.         next=(*stack)->next;
  51.         free(*stack);
  52.         *stack=next;
  53.     }
  54.     return 0;
  55. }
  56.  
  57. int main(){
  58.    
  59.     Element *stack;
  60.     int i=5;
  61.     int *o;
  62.    
  63.     createStack(&stack);
  64.     if(push(&stack,&i)==1)
  65.         printf("Error pushing\n");
  66.    
  67.     if(pop(&stack,&o)==1)
  68.         printf("Error poping\n");
  69.    
  70.     printf("o: %d\n",*o);  
  71.    
  72.     return 0;
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement