数据结构之表(6)栈的链接实现
代码如下:
# include <stdio.h> # include <stdlib.h> /*存储结构的定义*/ struct ds_node { int data ; struct ds_node * next ; }; /*入栈*/ void ds_push(struct ds_node **top,int item) { struct ds_node * temp ; temp = (struct ds_node *)malloc(sizeof(struct ds_node)) ; if(!temp) exit(0) ; temp->data = item ; temp->next = *top ; *top = temp ; } /* 判断栈是否为空 */ int ds_isEmpty(struct ds_node * top) { if(!top) /* 栈为空 */ return 1; else /* 栈不为空 */ return 0 ; } /*出栈*/ int ds_pop(struct ds_node ** top) { if(!ds_isEmpty(*top)) { struct ds_node * temp ; int elem = (*top)->data ; temp = *top ; /*取得栈顶的值*/ *top = (*top)->next ; free(temp) ; return elem ; } else /*栈为空*/ return 0 ; }
测试程序
int main() { struct ds_node * s = NULL ; printf("数据入栈按如下顺序:1,2,3\n") ; ds_push(&s,1) ; ds_push(&s,2) ; ds_push(&s,3) ; printf("判断是否为空:(0不为空,1为空)") ; printf("%d\n",ds_isEmpty(s)) ; printf("数据出栈顺序如下:") ; printf("%d ",ds_pop(&s)) ; printf("%d ",ds_pop(&s)) ; printf("%d",ds_pop(&s)) ; printf("\n") ; printf("判断是否为空:(0不为空,1为空)") ; printf("%d",ds_isEmpty(s)) ; getchar(); return 0 ; }
运行结果: