代码示例_数据结构_链式栈

链式栈


 static.h

 1 #pragma once
 2 
 3 #include <stdio.h>
 4 #include<stdlib.h>
 5 #include<malloc.h>
 6 
 7 
 8 typedef struct node{
 9     int data;
10     struct node *next;
11 }node;
12 
13 
14 typedef struct stack{
15     node *top;
16     int count;
17 }sta;
18 
19 
20 sta* init_stack(void);
21 int push(sta *s,int input);
22 int pop(sta *s);

static.c

 1 #include "stack.h"
 2 
 3 
 4 // 初始化栈
 5 sta* init_stack(void){
 6     sta *s = (sta*)malloc(sizeof(sta));
 7     if(s==NULL){
 8         perror("malloc failed!");
 9         exit(1);
10     }
11 
12     s->top   = NULL;
13     s->count = 0;
14     return s;
15 }
16 
17 
18 // 入栈
19 int push(sta *s,int input){
20     
21     node *pnew = (node*)malloc(sizeof(node));
22     if(pnew==NULL){
23         perror("malloc failed!");
24         exit(1);
25     }
26 
27     pnew->data = input;
28     pnew->next = s->top;
29     s->top     = pnew;
30 
31     s->count++;
32 
33      printf("input =  %d  入栈成功\n",input);
34 
35 }
36 
37 
38 // 出栈
39 int pop(sta *s){
40 
41     printf("output =  %d  出栈成功\n",s->top->data);
42     node *pnew = s->top;
43     int a = s->top->data;
44     s->top = s->top->next;
45 
46     s->count--;
47     free(pnew);
48 
49     return a;
50 
51 }

main.c

 1 #include "stack.h"
 2 
 3 int main(void)
 4 {
 5     sta *s = init_stack();
 6 
 7     int i = 0;
 8     for(i=0;i<5;i++){
 9 
10         push(s,i);
11 
12     }
13 
14 printf("\n------------------\n\n");
15 
16     for(i=0;i<5;i++){
17 
18         pop(s);
19 
20     }
21 
22 
23     return 0;
24 }

测试:


success !

猜你喜欢

转载自www.cnblogs.com/panda-w/p/11081129.html
今日推荐