Article Directory
- The basic operation of the chain stack
-
- 1. The structure definition of the chain stack
- 2. Initialization of the chain stack
- 3. Determine whether the chain stack is empty
- 4. Insert a new top element into the chain stack
- 5. Access the top element of the stack
- 6. Pop the top element of the stack
- 7. Traverse the chain stack from the top of the stack
The basic operation of the chain stack
1. The structure definition of the chain stack
typedef struct StackNode
{
ElemType data;
struct StackNode* next;
}StackNode, *LinkStack;
2. Initialization of the chain stack
/*
@description: 链栈的初始化
@return:
@author: sch
*/
bool InitLinkStack(LinkStack &S)
{
S = NULL;
return success;
}
3. Determine whether the chain stack is empty
/*
@description: 判断链栈是否为空
@return:
@author: sch
*/
bool isEmpty(LinkStack &S)
{
if(!S)
return true;
else return false;
}
4. Insert a new top element into the chain stack
/*
@description: 向链栈插入栈顶元素
@return:
@author: sch
*/
bool Push(LinkStack &top, ElemType e)
{
StackNode* p = (StackNode*) malloc(sizeof(struct StackNode));
if(!p)
{
free(p);
return failed;
}
p->data = e;
p->next = top;
top = p;
return success;
}
5. Access the top element of the stack
/*
@description: 访问链栈的栈顶元素
@return: 若栈为空返回NULL, 反之返回栈顶结点的地址
@author: sch
*/
StackNode* GetTop(LinkStack& top)
{
return top;
}
6. Pop the top element of the stack
/*
@description: 弹出链栈栈顶元素
@return:
@author: sch
*/
bool Pop(LinkStack &top)
{
if(!top)return failed;
StackNode* p = top;
top = top->next;
free(p);
return success;
}
7. Traverse the chain stack from the top of the stack
/*
@description: 从栈顶开始遍历链栈
@return:
@author: sch
*/
void LinkStackTraverse(LinkStack top)
{
StackNode* p = top;
while(p)
{
printf("%d\n", p->data);
p = p->next;
}
}