鏈棧的實現

#include<stdlib.h>node

#include<stdio.h>指針

#include<malloc.h>code

typedef int DataType;it

typedef struct node{ struct node *next;//指針域 DataType data;//數據域 }Stack;io

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

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

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

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

int StackGet(Stack *head,DataType *x);//取棧頂元素co

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); } }

相關文章
相關標籤/搜索