栈
初稿:2017-11-19 19:27:06
- 利用数组模拟的栈:
初始化 top = -1; 入栈 stack[++top] = elem ; 出栈 --top; 栈满 top == STACK_SIZE - 1; 栈空 top == -1
- 利用单链表模拟的栈:
参数只需要头结点即可,每个入栈元素 q 插在头结点的后面,q->next =pHead->next; pHead->next = q; 出栈时,pHead->next = pHead->next->next; 栈空: pHead->next == null;
顺序栈C代码: #define INIT_STACK_SIZE 100 #define STACK_INCREMENT 10 typedef int Status; typedef int ElemType; typedef struct { ElemType* base;//基址 ElemType* top;//栈顶元素的下一个空位 int maxsize;//栈的最大容量 }SqStack; Status InitStack(SqStack* S) { (*S).base = (ElemType*)malloc(sizeof(ElemType)*INIT_STACK_SIZE); if(!(*S).base) exit(-1); (*S).top = (*S).base;//空栈 (*S).maxsize = INIT_STACK_SIZE;//栈容量 return ok; } Status DestroyStack(SqStack* S) { free((*S).base); (*S).base = NULL; (*S).top = NULL; (*S).maxsize = 0; return ok; } Status ClearStack(SqStack* S) { (*S).top = (*S).base; return ok; } Status StackEmpty(SqStack S) { return S.top == S.base?true:false; } int StackLength(SqStack S) { return S.top - S.base; } Status Push(SqStack* S,ElemType e) { if((*S).top - (*S).base ==(*S).maxsize) { ElemType* p = (ElemType*)realloc((*S).base,sizeof(ElemType)*((*S).maxsize+STACK_INCREMENT)); if(!p) exit(-1); (*S).base = p; (*S).top=(*S).base+(*S).maxsize;//C语言的realloc用法细节,易忽视处 (*S).maxsize += STACK_INCREMENT; } *(*S).top++ = e; return ok; } Status Pop(SqStack* S,ElemType* e) { if(StackEmpty(*S)) return error; *e = *--(*S).top; return ok; } Status TraverseStack(SqStack S) { if(StackEmpty(S)) return error; while(S.base!=S.top) { printf("%d\t",*S.base); ++S.base; } printf("\n"); return ok; } 链栈C代码: typedef int Status; typedef int ElemType; typedef struct Node { ElemType data;//数据域 struct Node* next;//上一个节点的地址,而非下一个节点的地址 }SNode; typedef struct { SNode* top;//栈顶元素 int count;//计数器 }LinkStack; Status InitLStack(LinkStack* S) {//空栈,头节点 (*S).top = (SNode*)malloc(sizeof(SNode)); if(!(*S).top) exit(-1); (*S).top->next = NULL; (*S).count = 0; return ok; } Status PUSH(LinkStack*S,ElemType e) { SNode* p = (SNode*)malloc(sizeof(SNode)); if(!p) exit(-1); (*p).data = e; (*p).next = (*S).top;//新节点保存当前栈顶元素的地址 (*S).top = p;//更新栈顶top参数,使其指向新节点 (*S).count++; return ok; } Status PoP(LinkStack*S,ElemType*e) { SNode* p;//临时保存待删除节点的地址,释放之 if((*S).count == 0) return error; p = (*S).top; *e = (*p).data; (*S).top = p->next; free(p);//C语言中删除意味着free p = NULL; (*S).count--; return ok; }