链表&栈.

链栈

#include "link_stack.h"
//申请结点
node_p create_node(int data)
{
    node_p new = (node_p)malloc(sizeof(node));
    if(new==NULL)
    {
        printf("空间申请失败\n");
        return NULL;
    }
    new->data = data;
    return new;
}
//入栈
void push_stack(node_p *T,int data)
{
    //不再需要入参为空的判断,因为T就在栈区
    node_p new = create_node(data);
    new->next = *T;  //让新结点指向原来的栈顶元素
    *T = new;   //让栈顶指针指向新结点
}
//判空
int empty_stack(node_p T)
{
    return T==NULL?1:0;
}
//出栈
void pop_stack(node_p *T)
{
    node_p del = *T;   //保存要释放的结点的首地址
    *T =(*T)->next;
    printf("要出栈的元素为%d\n",del->data);
    free(del);
}
//输出栈
void show_stack(node_p T)
{    
    if(empty_stack(T))
    {
        printf("栈为空,无需输出\n");
        return;
    }
    node_p  p = T;
    while(p!=NULL)
    {
        printf("%d->",p->data);
        p=p->next;
    }

顺序栈

#include "seq_stack.h"
//堆区申请顺序栈的空间
seq_p create_stack()
{
    //堆区申请空间
    seq_p S = (seq_p)malloc(sizeof(seq_stack));
    //判断空间是否申请成功
    if(S==NULL)
    {
        printf("空间申请失败\n");
        return NULL;
    }
    //申请成功后,给data和top初始化
    S->top = -1;  //栈中没有元素时,让top指向-1位置
    return S;
}
//入栈/压栈
void push_stack(seq_p S,datatype data)
{
    //入参为空的判断
    if(S==NULL)
    {
        printf("空间申请失败\n");
        return;
    }
    //判满
    if(full_stack(S))
    {
        printf("栈已满\n");
        return;
    }
    //入栈
    //先加再压   先自增top指针,再将数据压入栈
    S->top++;
    S->data[S->top] = data;
    //S->data[++(S->top)]=data;
}
//判空
int empty_stack(seq_p S)
{
    if(S==NULL)
    {
        printf("入参为空\n");
        return -1;
    }
    return S->top==-1?1:0;
}
//判满
int full_stack(seq_p S)
{
    if(S==NULL)
    {
        printf("入参为空\n");
        return -1;
    }
    return S->top==MAX-1?1:0;
}
//输出栈
void show_stack(seq_p S)
{
    if(S==NULL)
    {
        printf("空间申请失败\n");
        return;
    }
    if(empty_stack(S))
    {
        printf("栈为空\n");
        return;
    }
    //要求输出顺序和栈操作的顺序一致
    for(int i=S->top;i>=0;i--)
    {
        printf("%-4d",S->data[i]);
    }
    /*while(S->top!=-1)
    {
        printf("%-4d",S->data[S->top]);
        S->top--;
    }*/
    putchar(10);
}
//出栈/弹栈
void pop_stack(seq_p S)
{
    if(S==NULL)
    {
        printf("空间申请失败\n");
        return;
    }
    if(empty_stack(S))
    {
        printf("栈为空\n");
        return;
    }
    //出栈只需将top指针自减即可
    printf("出栈元素为%d\n",S->data[S->top--]);    
}
//释放顺序栈
void free_stack(seq_p *S)
{
    //入参为空的判断
    if(S==NULL||*S==NULL)
    {
        printf("入参为空\n");
        return;
    }
    free(*S);
    *S=NULL;
}
 

  • 13
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值