#include <stdio.h> #include <stdlib.h> typedef struct _Node{ char data; struct _Node *next; }Node; typedef struct _Stack{ Node * top; }Stack; void initStack(Stack *s){ s->top = (Node*)malloc(sizeof(Node)); // 这里的链栈具有头节点,严蔚敏书没有头节点(可以有) s->top->next = NULL; } int isStackEmpty(Stack *s){ return s->top->next == NULL; } void push(Stack *s, char ch){ Node * cur = (Node*)malloc(sizeof(Node)); cur->data = ch; cur->next = s->top->next; // 头插法建立链栈,top指向新插入的地方,便于弹栈 s->top->next = cur; } char pop(Stack *s){ Node * t = s->top->next; char ch = t->data; s->top->next = t->next; free(t); return ch; } void resetStack(Stack *s){ while(!isStackEmpty(s)) pop(s); } void clearStack(Stack *s){ resetStack(s); free(s->top); } void dispStack(Stack *s){ Node *p=s->top->next; int i=0; while(p){ printf("%c ",p->data); p=p->next; i++; } printf("\nStack Length:%d\n",i); } int main(){ Stack s; initStack(&s); for(char ch = 'A'; ch <='Z'; ch++) { push(&s,ch); } //resetStack(&s); dispStack(&s); while(!isStackEmpty(&s)) { printf("%c ",pop(&s)); } clearStack(&s); return 0; }