来源:互联网 发布:云计算项目 编辑:程序博客网 时间:2024/05/20 17:24
  1. #include<stdio.h>  
  2. #include<stdlib.h>  
  3. #include<time.h>  
  4.   
  5. struct node  
  6. {  
  7.     int num;  
  8.     struct node*next;  
  9. };  
  10. typedef struct node Node;  
  11. struct stacklink  
  12. {  
  13.     Node *top;  
  14. };  
  15. typedef struct stacklink Stack;  
  16.   
  17. void create_stack(Stack **stack)  
  18. {  
  19.     (*stack) = (Stack*)malloc(sizeof(Stack));  
  20.     if((*stack)  == NULL)  
  21.     {  
  22.         printf("malloc error!\n");  
  23.         exit(-1);  
  24.     }  
  25. }  
  26. void init_stack(Stack **stack)  
  27. {  
  28.     (*stack)->top = NULL;  
  29. }  
  30. void push_stack(Stack**stack,int num)  
  31. {  
  32.     Node *newnode = NULL;  
  33.     newnode = (Node*)malloc(sizeof(Node));  
  34.     if(newnode == NULL)  
  35.     {  
  36.         printf("malloc error!\n");  
  37.         exit(-1);  
  38.     }  
  39.     newnode->num = num;  
  40.     if((*stack)->top == NULL)  
  41.     {  
  42.         (*stack)->top = newnode;  
  43.         newnode->next = NULL;  
  44.     }  
  45.     else  
  46.     {  
  47.         newnode->next = (*stack)->top;  
  48.         (*stack)->top = newnode;  
  49.     }  
  50. }  
  51.   
  52. int pop_stack(Stack **stack)  
  53. {  
  54.     int num;  
  55.     if((*stack)->top == NULL)  
  56.     {  
  57.         printf("stack is empty\n");  
  58.         return -1;  
  59.     }  
  60.     num =(*stack)->top->num;  
  61.     free((*stack)->top);  
  62.     (*stack)->top = (*stack)->top->next;  
  63.     return num;  
  64. }  
  65. int main()  
  66. {  
  67.     Stack *stack;  
  68.     int i;  
  69.     int tmp;  
  70.     int result;  
  71.     srand(time(NULL));  
  72.     create_stack(&stack);  
  73.     init_stack(&stack);  
  74.   
  75.     for(i=0;i<10;i++)  
  76.     {  
  77.         tmp = rand() % 100;  
  78.         if(tmp > 50)  
  79.         {  
  80.             push_stack(&stack,i);  
  81.             printf("push num %d\n",i);    
  82.         }  
  83.         else  
  84.         {  
  85.             result = pop_stack(&stack);  
  86.             if(result  != -1)  
  87.             {  
  88.                 printf("pop  num %d\n",result);  
  89.             }  
  90.         }  
  91.     }  
  92.   
  93.     return 0;  
  94. }  
0 0
原创粉丝点击