数据结构 -- 用C实现链式栈

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

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

int gettop(struct node *top)
{
    return top -> data;
}

struct node * push(struct node *top,int x )
{
    struct node *p;
    p = (struct node *)malloc(sizeof(struct node));
    p->data = x;
    p->next = top;
    top = p;
    return top;
}
struct node * pop(struct node *top)
{
    struct node *p;
    if(!top)
        return NULL;
    p = (struct node *)malloc(sizeof(struct node));
    p = top;
    top = top->next;
    free(p);
    return top;
}

int stempty(struct node *top)
{
    return(top->next==NULL ? 0 : 1);
}

int main()  //用于测试
{
    struct node *top;
    int n;  //栈的长度
    top = (struct node *)malloc(sizeof(struct node));
    top->next = NULL;

    int a[6] = {1,2,3,4,5,6},t = 7;//测试数据
    int i;
    for(i=0; i<6; i++)
    {
        top = push(top,a[i]);
    }
    top = push(top,t);
    top = pop(top);
    top = pop(top);
    printf("%d\n",gettop(top));
    while(top->next !=NULL)
    {
        printf("%d ",top->data);
        printf("%d\n",stempty(top));
        top=top->next;
    }
    printf("%d\n",stempty(top));
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值