数据结构--栈--链式存储
栈的链式存储跟线性表的链式存储一样,只是添加删除数据的方式不同。
编译器:GCC
#include <stdio.h> typedef int elemType; struct sNode{ elemType data; struct sNode *next; }; /* 1.初始化栈为空*/ void initStack(struct sNode **hs) { *hs = NULL; return; } /* 2.向链中插入一个元素(入栈) */ void push(struct sNode **hs, elemType x) { struct sNode *temp; temp = (struct sNode *)malloc(sizeof(struct sNode)); if(temp == NULL) { printf("空间申请失败...\n"); system("pause"); } temp->next = *hs; temp->data = x; *hs = temp; return; } /* 3.从链栈中删除一个元素并返回它(出栈)*/ elemType pop(struct sNode **hs) { if(*hs == NULL) { printf("栈空,出栈失败...\n"); system("pause"); } struct sNode *temp; elemType data = (*hs)->data; temp = *hs; *hs= (*hs)->next; free(temp); return data; } /* 4.读取栈顶元素*/ elemType peek(struct sNode **hs) { if(*hs == NULL) { printf("栈空,出栈失败...\n"); return -1; } return (*hs)->data; } /* 5.判断链栈是否为空,为空返回1,否则返回0*/ int emptyStack(struct sNode **hs) { if(*hs == NULL) { return 1; }else{ return 0; } } /* 6.清除链栈为空*/ void clearStack(struct sNode **hs) { while(*hs != NULL) { pop(hs); } return; } /*******************************************************/ int main(void) { struct sNode *s; int a[8] = {3,8,5,17,9,30,15,22}; int i; initStack(&s); printf("初始化栈...\n"); for(i=0; i<8; i++) { printf("%d ",a[i]); push(&s, a[i]); } printf("\n操作顺序:pop pop push(68) pop pop \n"); printf("%d ",pop(&s)); printf("%d ",pop(&s)); push(&s, 68); printf("%d ",pop(&s)); printf("%d ",pop(&s)); printf("\npop出剩余的...\n"); while(!emptyStack(&s)) { printf("%d ", pop(&s)); } printf("\n"); clearStack(&s); system("pause"); return 0; }
************************************************************************
运行结果:
************************************************************************
初始化栈... 3 8 5 17 9 30 15 22 操作顺序:pop pop push(68) pop pop 22 15 68 30 pop出剩余的... 9 17 5 8 3 请按任意键继续. . .