自学内容网 自学内容网

栈————day6

1、顺序栈

  1. 创建栈
  2. 入栈
  3. 遍历栈
  4. 出栈
  5. 获取元素
  6. 求栈大小
  7. 销毁栈
#include <stdio.h>
#include <stdlib.h>

#define MAX 5
typedef struct
{
int data[MAX];
int top;
}stack,*Pstack;
Pstack create()
{
Pstack p = malloc(sizeof(stack));
if(NULL==p)
{
printf("创建栈失败\n");
return NULL;
}
p->top = -1;
return p;//返回栈地址
}
int push(Pstack Z,int e)
{
if(Z->top==MAX-1)//判断栈满
{
printf("栈满无法入栈\n");
return -1;
}
//入栈先加后压
Z->top++;
Z->data[Z->top] = e;
printf("入栈成功\n");
return 0;
}
int pop(Pstack Z)
{
if(Z->top==-1)//判断栈空
{
printf("栈空无法出栈\n");
return -1;
}
//出栈先弹后减
printf("%d\t",Z->data[Z->top]);
Z->top--;
return 0;
}
int output1(Pstack Z)
{
if(Z->top==-1)
{
printf("栈空,无法输出\n");
return -1;
}

int i;
for(i  =0;i<=Z->top;i++)
{
printf("%d\t",Z->data[i]);
}
printf("\n");
return 0;
}
int output2(Pstack Z)
{
if(Z->top==-1)
{
printf("栈空,无法输出\n");
return -1;
}

int i;
for(i  =Z->top;i>=0;i--)
{
printf("%d\t",Z->data[i]);
}
return 0;
}
int huoqu(Pstack Z)
{
if(Z->top==-1)
{
printf("获取失败\n");
return -1;
}
return Z->data[Z->top];
}
int sizestack(Pstack Z)
{
return Z->top+1;
}
int destroy_stack(Pstack Z)
{
free(Z);
Z=NULL;
printf("销毁成功\n");
return 0;
}
int main(int argc, const char *argv[])
{
Pstack Z = create();
push(Z,10);
push(Z,20);
push(Z,30);
push(Z,40);

printf("栈底到栈顶\n");
output1(Z);//从栈顶到栈底输出

printf("栈顶到栈底\n");
output2(Z);//从栈底到栈顶输出

printf("栈顶元素:%d\n",huoqu(Z));//获取栈顶元素

printf("栈的大小:%d\n",sizestack(Z));

int i,k = Z->top;

printf("\n依次出栈:");
for(i = 0;i<=k;i++)
{
pop(Z);
}

destroy_stack(Z);//销毁栈
return 0;
}

 

2、链式栈

  1. 创建栈
  2. 入栈
  3. 遍历栈
  4. 出栈
  5. 销毁栈
#include <stdio.h>
#include <stdlib.h>


typedef struct node//正常节点结构体
{
int data;
struct node *next;
}xxx,*Pxxx;
typedef struct//栈顶指针的结构体
{
int len;
Pxxx top;
}stack,*Pstack;
Pstack create()//创建栈顶指针节点
{
Pstack p = malloc(sizeof(stack));
if(p==NULL)
{
printf("申请节点失败\n");
return NULL;
}
p->len=0;
p->top=NULL;
return p;
}
int push(Pstack S,int e)//入栈
{
if(S==NULL)
{
printf("入栈失败\n");
return -1;
}
Pxxx p = malloc(sizeof(xxx));
p->data = e;

p->next = S->top;
S->top = p;

S->len++;
printf("入栈成功\n");
return 0;
}
int pop(Pstack S)//出栈
{
if(S->top==NULL||S==NULL)
{
printf("栈空出栈失败\n");
return -1;
}

Pxxx Q = S->top;
printf("出栈元素是:%d\n",Q->data);
S->top = Q->next;
free(Q);
Q = NULL;
S->len--;
return 0;
}
int ouput_stack(Pstack S)//输出
{
if(S==NULL||S->top==NULL)
{
printf("栈不存在或者空\n");
return -1;
}
Pxxx t = S->top;
while(t!=NULL)
{
printf("%d\t",t->data);
t = t->next;
}
return 0;
}
int main(int argc, const char *argv[])
{

Pstack S = create();//栈顶指针top创建完成
push(S,100);
push(S,200);
push(S,300);
push(S,400);

pop(S);//出栈
pop(S);//出栈

ouput_stack(S);


return 0;
}

 


原文地址:https://blog.csdn.net/m0_74933801/article/details/142497419

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!