链栈的实现

#include<stdlib.h>

#include<stdio.h>

#include<malloc.h>

typedef int DataType;

typedef struct node{ struct node *next;//指针域 DataType data;//数据域 }Stack;

void initStack(Stack **head);//初始化

int isEmpty(Stack *head);//判非空否

int StackPush(Stack *head,DataType x);//入栈

int StackPop(Stack *head,DataType *x);//出栈

int StackGet(Stack *head,DataType *x);//取栈顶元素

void Destory(Stack *head);//撤销栈

int main(void){ int x,i; Stack *stack; initStack(&stack); for(i=0;i<10;i++) StackPush(stack,i+1); for(i=0;i<10;i++) { StackPop(stack,&x); printf("x=%d\n",x); }

isEmpty(stack);
return 0;

}

void initStack(Stack **head){ *head=(Stack *)malloc(sizeof(Stack));//动态申请 (*head)->next=NULL;//将头指针的next域设为空 }

int StackPush(Stack *head,DataType x){ Stack *p; p=(Stack *)malloc(sizeof(Stack)); p->data=x; p->next=head->next; head->next=p; printf("入栈成功\n"); return 0; }

int isEmpty(Stack *head){ Stack *p=head->next; if(p!=NULL){ printf("栈非空\n"); return 1; } printf("栈空\n"); return 0; }

int StackPop(Stack *head,DataType *x){ Stack *p=head->next; if(p==NULL){ printf("链栈已空\n"); return 0; } head->next=p->next; *x=p->data; free(p); printf("出栈成功\n"); return 1; }

int StackGet(Stack *head,DataType *x){ Stack *p; p=head->next; if(p==NULL){ printf("取栈顶元素为空\n"); return 0; }

*x=p->data;
return 1;

}

void Destory(Stack *head){ Stack *p,*q; p=head; while(p!=NULL){ q=p; p=p->next; free(q); } }

猜你喜欢

转载自my.oschina.net/u/2511906/blog/1623292