关于栈的基本概念以及和Catalan数的关系,可以参见我的其他文章
参考资料《数据结构与算法分析——C语言描述》
#include<stdio.h> #include<stdlib.h> /*栈的链表实现*/ typedef struct StackNode { struct StackNode *next; int data; }StackNode,*Stack; Stack CreateStack(void);//创建一个空栈 void MakeEmpty(Stack S);//清空栈 int IsEmpty(Stack S);//测试是否是空栈 void Push(int data,Stack S);//入栈 void Pop(Stack S);//出栈 int Top(Stack S);//返回栈顶元素 int main() { Stack SP=NULL; SP=CreateStack(); Push(5,SP); Push(4,SP); Push(8,SP); printf("%d\n",Top(SP)); Pop(SP); printf("%d\n",Top(SP)); return 0; } Stack CreateStack(void) { Stack S; S=malloc(sizeof(StackNode)); if(S==NULL) printf("out of space!\n"); S->next=NULL; MakeEmpty(S); return S; } void MakeEmpty(Stack S) { if(S==NULL) printf("Please Create Stack First!\n"); else while(!IsEmpty(S)) Pop(S); } int IsEmpty(Stack S) { return S->next==NULL; } void Push(int data,Stack S) { Stack tmp; tmp=malloc(sizeof(StackNode)); if(tmp==NULL) printf("out of space!\n"); else { tmp->data=data; tmp->next=S->next; S->next=tmp; } } void Pop(Stack S) { Stack tmp; if(IsEmpty(S)) printf("empty stack!\n"); else { tmp=S->next; S->next=S->next->next; free(tmp); } } int Top(Stack S) { if(!IsEmpty(S)) return S->next->data; else printf("empty stack!\n"); return 0; }
原文:http://blog.csdn.net/u010275850/article/details/44947129