以前参照weiss的《数据结构与算法分析》写过两篇随笔
因为考研的缘故,现在看了严蔚敏的《数据结构 c版》也跟着写了一遍,原理都类似
链栈:
/*链栈*/ typedef status typedef struct node Stack; typedef struct node * ptrToNode; struct node { int data; ptrToNode next; }; Status initStack(Stack &S) { S.next = NULL; return OK; } Status getTop(Stack &S, struct node &e) { if(!stackEmpty(S)) return ERROR; e = *(S.next); return OK; } Status Push(Stack &S, int e) { ptrToNode tmp = (ptrToNode)malloc(sizeof(struct node)); tmp->data = e; tmp->next = S.next; S.next = tmp; return OK; } int stackEmpty(Stack &S) { return (S.next == NULL); } Status Pop(Stack &S, int &e) { ptrToNode tmp = S.next; e = tmp->data; S.next = tmp->next; free(tmp); return OK; }
顺序栈:
#define STACK_INIT_SIZE 100; #define INCREMENT 10; struct node { SElementType * next; }; //struct的申明方式 typedef struct node SElementType; typedef struct { SElementType * base; SElementType * top; int stackSize; }SqStack; Status initStack(SqStack &S) { S.base = S.top = (SElementType *)malloc(sizeof(SElementType) * STACK_INIT_SIZE); if(!S.base) exit(OVERFLOW);//failed to malloc cuncu S.stackSize = STACK_INIT_SIZE; } Status getTop(SqStack &S,SElementType &e) { if(S.base == S.top) return ERROR; e = *(S.top-1); return OK; } Status Push(SqStack &S,SElementType e) { if(S.top - S.base == S.stackSize) { //search the result of realloc S.base = (SElementType *)realloc(S.base, sizeof(SElementType) * (STACK_INIT_SIZE + INCREMENT)); if(!S.base) exit(OVERFLOW); S.top = S.base + S.stackSize; S.stackSize += INCREMENT; } *S.top++ = e; return OK; } Status Pop(SqStack &S,SElementType &e) { if(S.base == S.top) return ERROR; S.top--; e = *S.top; return OK; }
差别:
相同点:
原文:http://www.cnblogs.com/gabygoole/p/5591604.html