链栈的一些操作

头文件

#ifndef _LINKSTACK_H_
#define _LINKSTACH_H_

#define SUCCESS 10000
#define FAILURE 10001

typedef  int ElemType;
struct node
{
    ElemType data;
    struct node *next;
};
typedef struct node Node;
typedef Node *LinkNode;

struct stack
{
    LinkNode top;
    int count;
};
typedef struct stack Stack;



#endif

接口函数

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


int StackInit(Stack **S)
{
    (*S) = (Stack *)malloc(sizeof(Node));
    if(NULL == (*S))
    {
        return FAILURE;
    }
    (*S)->top = NULL;
    (*S)->count = 0;

    return SUCCESS;
}

int PUSH(Stack *S,ElemType e)
{
    Node *p = (Node *)malloc(sizeof(Node));
    if(NULL == p)
    {
        return FAILURE;
    }
    p->data = e;
    p->next = S->top;
    S->top = p;
    S->count++;

    return SUCCESS;
}

int StackLength(Stack *S)
{
    return (S->count);
}

int GetTop(Stack *S,ElemType *e)
{
    if(NULL == S->top)
    {
        return FAILURE;
    }

    *e = S->top->data;

    return SUCCESS;
}

int Pop(Stack *S,ElemType *e)
{
    if(NULL == S->top)
    {
        return FAILURE;
    }

    LinkNode p = S->top;
    S->top = p->next;
    *e = p->data;
    free(p);
    S->count++;

    return SUCCESS;
}

int Clear(Stack *S)
{
    LinkNode p;
    while(S->top)
    {
        p=S->top;
        S->top=p->next;
        free(p);
        S->count--;
    }

}

int Destroy(Stack **S)
{
    if(NULL==(*S))
    {
        return FAILURE;
    }
    free(*S);
    *S=NULL;
    return SUCCESS;
}

主函数

#include<stdio.h>
#include"LinkStack.h"

int main()
{
    int ret,i;
    Stack *s;
    ElemType e;

    ret=StackInit(&s);
    if (FAILURE == ret)
    {
        printf("Init Failure!\n");

    }
    else
    {
        printf("Init Success!\n");
    }

    for(i=0;i<5;i++)
    {
        e=i+1;
        ret = PUSH(s,e);
        if(FAILURE == ret)
        {
            printf("Push Failure!\n");
        }
        else
        {
            printf("Push %d Success !\n",e);
        }
    }

printf("Length is %d\n",StackLength(s));

ret=GetTop(s,&e);
if(FAILURE == ret)
{
    printf("Get Failure!\n");
}
else
{
    printf("Get %d Success!\n",e);
}

for(i=0;i<2;i++)
{
    ret = Pop(s,&e);
    if(FAILURE ==ret)
    {
        printf("Pop Failure!\n");
    }
    else
    {
        printf("Pop %d Success!\n",e);
    }
}

ret=Clear(s);
if(FAILURE==ret)
{
    printf("Clear Failure!\n");
}
else
{
    printf("Clear Success!\n");
}

ret = Destroy(&s);
if(FAILURE==ret)
{
    printf("Destroy Failure!\n");
}
else
{
    printf("Destroy Success!\n");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值