C语言栈结构实现

顺序栈

//实现十进制转八进制

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

struct seq_stack
{
    int *data;
    int size;
    int top;
};

struct seq_stack *init_stack(int size)
{
    struct seq_stack *head = (struct seq_stack*)malloc(sizeof(struct seq_stack));
    if(head != NULL)
    {
        head->data = (int *)calloc(size, sizeof(int));
        head->size = size;
        head->top = -1;
    }
    return head;
}

bool is_full(struct seq_stack *s)
{
    return s->top >= s->size;
}

bool push(struct seq_stack *s, int num)
{
    if(is_full(s))
        return false;

    s->data[++s->top] = num;
    return true;
}

bool is_empty(struct seq_stack *s)
{
    return s->top == -1;
}

bool pop(struct seq_stack *s, int *pm)
{
    if(is_empty(s))
        return false;

    *pm = s->data[s->top--];
    return true;
}

int main()
{
    struct seq_stack *s = init_stack(10);

    int n;
    scanf("%d",&n);

    while(n != 0)
    {
        if(!push(s, n%8))
        {
            printf("push is failed\n");
            exit(1);
        }
        n /= 8;
    }

    int m;
    printf("0");
    while(1)
    {
        if(!is_empty(s))
        {
            pop(s, &m);
            printf("%d",m);
        }
        else
            break;
    }
    printf("\n");
    return 0;
}


链式栈

通过next指针指向下一个数据,用一个大的结构体来存放top和size

好处是不用先指定栈的大小

//实现十进制转换为八进制
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

struct node
{
    int data;
    struct node *next;
};

struct stack
{
    struct node *top;
    int size;
};

struct stack *init_stack()
{
    struct stack *ne = (struct stack*)malloc(sizeof(struct stack));
    if(ne != NULL)
    {
        ne->size = 0;
        ne->top = NULL;
    }
    return ne;
}

void push(struct stack *s, int num)
{
    struct node *ne = (struct node*)malloc(sizeof(struct node));
    ne->data = num;
    ne->next = s->top;
    s->top = ne;
    s->size++;
}

bool is_empty(struct stack *s)
{
    return s->size == 0;
}

void pop(struct stack *s, int *pm)
{
    struct node *tmp = s->top;
    *pm = tmp->data;
    s->top = tmp->next;
    tmp->next = NULL;
    s->size--;
}

int main()
{
    struct stack *s = init_stack();

    int n;
    scanf("%d",&n);

    while(n > 0)
    {
        push(s, n % 8);
        n /= 8;
    }

    int m;
    printf("0");
    while(1)
    {
        if(is_empty(s))
            break;
        pop(s, &m);
        printf("%d",m);
    }
    printf("\n");
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值