栈顶指针和单链表的头指针合二为一
链栈的初始化操作就是构造一个空栈,因此没有必要设头节点,所以直接将栈顶指针置空即可
链栈在入栈前不需要判断栈是否满,只需要为入栈元素动态分配一个结点空间
#include <iostream>
using namespace std;
typedef int elemtype;
typedef int status;
typedef struct stacknode
{
elemtype data;
stacknode *next;
}stacknode,*linkstack;
//初始化
status initstack(linkstack &s)
{
s = NULL;
return 0;
}
//链栈的入栈
status push(linkstack &s,elemtype e)
{
linkstack p;
p = new stacknode;
p->data = e;
p->next = s;
s = p;//修改栈顶指针为p
return 0;
}
//出栈
status pop(linkstack &s,elemtype &e)
{
if (s == NULL)
return -1;
e = s->data;
linkstack p;
p = s;
s = s->next;
delete p;
return 0;
}
//取栈顶元素
status gettop(linkstack s)
{
if (s != NULL)
return s->data;
}