顺序存储结构下栈的基本操作
发布网友
发布时间:2022-05-09 20:19
我来回答
共1个回答
热心网友
时间:2023-10-17 12:01
/*
此程序仅供参考!
*/
# include <stdio.h>
# include <string.h>
# include <stdlib.h>
typedef struct Node
{
int data;
struct Node * pNext;
}NODE,* PNODE;
typedef struct Stack
{
PNODE pTop;
PNODE pBottom;
}STACK,* PSTACK;
void initiate(PSTACK pS);//创建一个空栈
void is_empty(PSTACK pS);//判断栈是否为空
int push(PSTACK pS);//压栈
int GetTop(PSTACK pS, int * pTop);//获取当前栈顶元素
void PrintStack(PSTACK pS);//遍历栈,不破环栈
int pop_one(PSTACK pS,int * pVal);//从栈中弹出一个元素
void Pop(PSTACK pS,int len);//遍历栈,破环栈
int main(void)
{
STACK s;
printf("创建一个空栈:......\n");
initiate(&s);
is_empty(&s);
int len = push(&s);
is_empty(&s);
int top;
top = GetTop(&s, &top);
printf("\n当前栈顶元素是%d\n",top);
printf("\n遍历栈(未破环栈)......\n");
PrintStack(&s);
is_empty(&s);
printf("\n遍历栈(破环栈)......\n");
Pop(&s,len);
is_empty(&s);
return 0;
}
void initiate(PSTACK pS)
{
pS->pTop = (PNODE)malloc(sizeof(NODE));
if (NULL == pS->pTop)
{
printf("动态内存分配失败!\n");
exit(-1);
}
else
{
pS->pBottom = pS->pTop ;
pS->pTop->pNext = NULL;
}
return;
}
int push(PSTACK pS)
{
printf("\n请输入栈的深度:\t");
int len;
scanf("%d",&len);
int i,val;
for (i=0; i<len; ++i)
{
printf("请输入第%d个元素:\t",(i+1));
scanf("%d",&val);
PNODE pNew = (PNODE)malloc(sizeof(NODE));
pNew->data = val;
pNew->pNext = pS->pTop ;
pS->pTop = pNew;
}
return len;
}
void PrintStack(PSTACK pS)
{
PNODE p = pS->pTop;
while (p != pS->pBottom)
{
printf("%5d",p->data);
p = p->pNext ;
}
printf("\n");
return;
}
void is_empty(PSTACK pS)
{
if (pS->pTop == pS->pBottom)
{
printf("\n当前栈为空!\n");
}
else
{
printf("\n当前栈不为空!\n");
}
return;
}
int pop_one(PSTACK pS,int * pVal)
{
PNODE r = pS->pTop;
*pVal = r->data ;
pS->pTop = r->pNext;
free(r);
r = NULL;
return * pVal;
}
int GetTop(PSTACK pS,int * pTop)
{
PNODE r = pS->pTop;
*pTop = r->data ;
return * pTop;
}
void Pop(PSTACK pS,int len)
{
int i,val;
for (i=0; i<len; ++i)
{
val = pop_one(pS,&val);
printf("%3d",val);
}
printf("\n");
return ;
}
/*
在vc++6.0中的输出结果是:
--------------------
创建一个空栈:......
当前栈为空!
请输入栈的深度: 5
请输入第1个元素: 1
请输入第2个元素: 2
请输入第3个元素: 3
请输入第4个元素: 4
请输入第5个元素: 5
当前栈不为空!
当前栈顶元素是5
遍历栈(未破环栈)......
5 4 3 2 1
当前栈不为空!
遍历栈(破环栈)......
5 4 3 2 1
当前栈为空!
-----------------------
*/