c语言 实现栈结构
main.c
# include "Stack.h"
# include <stdio.h>
int main ( ) {
Stack stack;
initStack ( & stack) ;
for ( ElemType i = 0 ; i <= 10 ; ++ i) {
push ( & stack, i) ;
}
resetStack ( & stack) ;
while ( ! isStackEmpty ( & stack) ) {
printf ( "%d " , pop ( & stack) ) ;
}
clearStack ( & stack) ;
return 0 ;
}
Stack.h
# ifndef __STACK_H__
# define __STACK_H__
# include <stdbool.h>
typedef int ElemType;
typedef struct _Node {
ElemType data;
struct _Node * next;
} Node;
typedef struct Stack {
Node * top;
} Stack;
void initStack ( Stack* ) ;
bool isStackEmpty ( Stack* ) ;
void push ( Stack* , ElemType) ;
ElemType pop ( Stack* ) ;
void resetStack ( Stack* ) ;
void clearStack ( Stack* ) ;
# endif
Stack.c
# include "Stack.h"
# include <stdlib.h>
# include <stdio.h>
void initStack ( Stack * s) {
s-> top= malloc ( sizeof ( Node) ) ;
s-> top-> next= NULL ;
}
bool isStackEmpty ( Stack * s) {
return s-> top-> next== NULL ;
}
void push ( Stack* s, ElemType data) {
Node * cur= ( Node * ) malloc ( sizeof ( Node) ) ;
cur-> data= data;
cur-> next= s-> top-> next;
s-> top-> next= cur;
}
ElemType pop ( Stack* s) {
Node * temp= s-> top-> next;
ElemType data= temp-> data;
printf ( "弹出:%d" , data) ;
s-> top-> next= s-> top-> next-> next;
free ( temp) ;
return data;
}
void resetStack ( Stack* s) {
while ( ! isStackEmpty ( s) ) {
pop ( s) ;
}
}
void clearStack ( Stack* s) {
resetStack ( s) ;
free ( s-> top) ;
} ```