数据结构---栈的链表实现

栈的链表实现C代码如下:

#include <stdio.h>

typedef int ElemType;


typedef struct node
{
    ElemType Data;
    struct node *next;
}Node;

typedef struct stack
{
    Node *top;
}Stack;

//初始化栈
void InitStack(Stack *S)
{
    S->top=NULL;
}

//入栈
int PushStackValue(Stack *S)
{
    printf("Input the Value of stack member:\n(0-exit)\n");
    int value;
    int i=1;
    Node *NewNode=(Node *)malloc(sizeof(Node));
    printf("Please input the %dst value of stack:\n",i);
    scanf("%d",&value);
    NewNode->Data=value;
    NewNode->next=S->top;
    S->top=NewNode;
    i++;
    while(value)
    {
        Node *NewNode=(Node *)malloc(sizeof(Node));
        printf("Please input the %dst value of stack:\n",i);
        scanf("%d",&value);
        if(value!=0)
            i++;
        NewNode->Data=value;
        NewNode->next=S->top;
        S->top=NewNode;
    }
    S->top=S->top->next;
    return i-1;
}

//出栈
int PopStackValue(Stack *S,int len)
{

    if(len>0)
    {
        printf("the stack %dst value pop out: %d\n",len,S->top->Data);
    }
    else
    {
        printf("The Stack is empty\n");
    }
    len--;
    S->top=S->top->next;
    return len;
}

//判断栈空
void IsEmpty(Stack *S)
{
    if(S->top==NULL)
    {
        printf("The Stack is empty.\n");
    }
    else
    {
        printf("The stack is not empty.\n");
    }
}


//清空栈
void ClearStack(Stack *S)
{
    S->top=NULL;
}

//遍历栈
Stack * ScanStack(Stack *S)
{
    Stack *Temp=S;
    printf("The all stack member(from top to bottom) is:\n");
    while(S->top!=NULL)
    {
        printf("%d ",S->top->Data);
        S->top=S->top->next;
    }
    printf("\n");

    return Temp;
}

void main()
{
    Stack *S=(Stack *)malloc(sizeof(Stack));
    int len;

    InitStack(&S);
    len=PushStackValue(&S);
    len=PopStackValue(&S,len);
    len=PopStackValue(&S,len);
    S=ScanStack(&S);
    IsEmpty(&S);
}

运行结果:





转载请注明作者:小刘

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值