- #include<stdio.h>
- #include<stdlib.h>
- #include<time.h>
- struct node
- {
- int num;
- struct node*next;
- };
- typedef struct node Node;
- struct stacklink
- {
- Node *top;
- };
- typedef struct stacklink Stack;
- void create_stack(Stack **stack)
- {
- (*stack) = (Stack*)malloc(sizeof(Stack));
- if((*stack) == NULL)
- {
- printf("malloc error!\n");
- exit(-1);
- }
- }
- void init_stack(Stack **stack)
- {
- (*stack)->top = NULL;
- }
- void push_stack(Stack**stack,int num)
- {
- Node *newnode = NULL;
- newnode = (Node*)malloc(sizeof(Node));
- if(newnode == NULL)
- {
- printf("malloc error!\n");
- exit(-1);
- }
- newnode->num = num;
- if((*stack)->top == NULL)
- {
- (*stack)->top = newnode;
- newnode->next = NULL;
- }
- else
- {
- newnode->next = (*stack)->top;
- (*stack)->top = newnode;
- }
- }
- int pop_stack(Stack **stack)
- {
- int num;
- if((*stack)->top == NULL)
- {
- printf("stack is empty\n");
- return -1;
- }
- num =(*stack)->top->num;
- free((*stack)->top);
- (*stack)->top = (*stack)->top->next;
- return num;
- }
- int main()
- {
- Stack *stack;
- int i;
- int tmp;
- int result;
- srand(time(NULL));
- create_stack(&stack);
- init_stack(&stack);
- for(i=0;i<10;i++)
- {
- tmp = rand() % 100;
- if(tmp > 50)
- {
- push_stack(&stack,i);
- printf("push num %d\n",i);
- }
- else
- {
- result = pop_stack(&stack);
- if(result != -1)
- {
- printf("pop num %d\n",result);
- }
- }
- }
- return 0;
- }
栈
最新推荐文章于 2023-04-10 21:40:26 发布