本文主要是介绍数据结构之链栈的所有操作,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct node
{
struct node * next;
int data;
}Node,*PNode;//定义节点类型
typedef struct stack
{
PNode top;
PNode bottom;
}Stack,*PStack;//定义栈类型。
void init_stack(PStack ps);
int isEmpty(PStack ps);
void push(PStack ps,int val);
void pop(PStack ps);
void traversal(PStack ps);
int main()
{
PStack stack = (PStack) malloc(sizeof(Stack));
init_stack(stack);
isEmpty(stack);
push(stack,1);
push(stack,2);
traversal(stack);
pop(stack);
push(stack,3);
push(stack,4);
traversal(stack);
printf("%d\n",isEmpty(stack));
return 0;
}
//初始化栈
void init_stack(PStack ps)
{
PNode pnew =(PNode) malloc(sizeof(Node));
if(pnew==NULL)
{
printf("初始化栈失败!\n");
exit(-1);
}
printf("初始化栈开始:\n");
ps->top=ps->bottom=pnew;
pnew->next=NULL;
printf("初始化栈成功!\n");
}
//判断栈是否为空
int isEmpty(PStack ps)
{
if(ps->top==ps->bottom)
{
printf("栈为空!\n");
return 1;
}
else
{
printf("栈不为为空!\n");
return 0;
}
}
//进栈
void push(PStack ps,int val)
{
PNode pnew = (PNode) malloc(sizeof(Node));
pnew->data = val;
pnew->next = ps->top;
ps->top = pnew;
printf("进栈成功!\n");
}
//出栈
void pop(PStack ps)
{
if(isEmpty(ps))
{
printf("栈为空!\n");
exit(-1);
}
else
{
PNode pnew = ps->top;
ps->top=ps->top->next;
free(pnew);
printf("出栈成功!\n");
}
}
//遍历
void traversal(PStack ps)//传的是栈的地址,所以不能通过再定义一个栈变量来遍历(遍历的过程中实际上还是改变栈的值),
{
/*PStack psn = ps;
printf("栈遍历开始:\n");
while(!isEmpty(psn))
{
printf("%d\n",psn->top->data);
psn->top=psn->top->next;
}
printf("栈遍历结束:\n");**/
PNode pnew = ps->top;
printf("栈遍历开始:\n");
while(pnew!=ps->bottom)
{
printf("%d\n",pnew->data);
pnew=pnew->next;
}
printf("栈遍历结束:\n");
}
这篇关于数据结构之链栈的所有操作的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!