栈的C语言实现

用C语言的指针实现了栈中的几项基本操作:新建栈,置空栈,进栈,弹栈,返回栈顶。
因为栈遵循后进先出的原则,所以我们的所有操作都是对于栈顶进行的。像上篇中单项链表的实现一样,在真正栈顶之前加上空节点指向它,将会便于对栈顶的操作。

用结构体指针定义栈:

1 typedef struct Node
2 {
3     char ele;
4     struct Node * next;
5 }Node;
6 
7 typedef Node * Stack;

新建栈:

1 Stack MakeStack(void)//新建栈并返回栈顶
2 {
3     Stack S = (Node *)malloc(sizeof(Node));
4     S->next = NULL;
5   return S;//返回的是假的栈顶
6 }

进栈:

1 void Push(Stack S, char c)//将新节点压入栈
2 {
3     Stack temp = (Node *)malloc(sizeof(Node));
4     temp->ele = c;
5     temp->next = S->next;
6     S->next = temp;
7 }

弹栈:

1 void Pop(Stack S)//将栈顶弹出
2 {
3     Stack temp = S->next;
4     S->next = temp->next;
5 }

返回栈顶:

1 Stack FindHead(Stack S)//返回栈顶
2 {
3     Stack temp = S->next;
4     return temp;
5 }

问题们:

需不需要加入栈底节点?这么做会带来什么好处吗?

posted @ 2017-10-31 19:37  菜菜大魔王  阅读(1341)  评论(0编辑  收藏  举报