#include<stdio.h> #include<malloc.h> #include<stdlib.h> #include<stdbool.h> typedef struct Node{ int data; struct Node* next; }Node; typedef struct Stack{ Node* top; Node* bottom; }Stack; void InitStack(Stack* stack){ Node* pNew = (Node*)malloc(sizeof(Node)); if(pNew == NULL){ printf("栈初始化失败!!"); exit(-1); } stack->bottom = pNew; stack->top = pNew; pNew->next = NULL; printf("栈创建成功 "); } void Push(Stack *stack,int value){ Node* pNew = (Node*)malloc(sizeof(Node)); if(pNew == NULL){ printf("push失败!"); exit(-1); } pNew->data = value; pNew->next = stack->top; stack->top = pNew; //printf("push%d成功! ",pNew->data); } int Pop(Stack *stack){ int result; if(stack->top == NULL){ printf("栈空! "); exit(-1); } Node *p = stack->top; result = p->data; stack->top = p->next; free(p); p = NULL; return result; } bool IsEmpty(Stack* stack){ if(stack->bottom == stack->top){ return true; }else{ return false; } } void TraverseStack(Stack* stack){ if(IsEmpty(stack)){ printf("栈为空! "); return; } Node* currNode = stack->top; while(currNode != stack->bottom){ printf("%d->",currNode->data); currNode = currNode->next; } } int main() { Stack stack; int i; InitStack(&stack); Push(&stack,100); printf("出栈%d ",Pop(&stack)); printf("进栈 "); for(i = 0;i<100;++i) { Push(&stack,i); } TraverseStack(&stack); }