使用C语言实现的栈

使用链表实现
my_stack.h

#ifndef MY_STACK_H
#define MY_STACK_H
#define elementType int

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

typedef struct node * Node;
typedef Node Stack;

void fatelError(const char * outprint);
int isEmpty(Stack stack);
void makeEmpty(Stack stack);
Stack createStack(void);
void makeEmpty(Stack stack);
void push(Stack stack, elementType data);
elementType top(Stack stack);
elementType pop(Stack stack);

void disposeStack(Stack stack);  
#endif

my_stack.c

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


// 打印错误消息并退出程序
void fatelError(const char * outprint)
{
  printf(outprint);
  fflush(stdout);
  exit(EXIT_FAILURE);
}


Stack createStack(void)
{
  Stack S = (Stack)malloc(sizeof(Stack));
  if (S == NULL)
    fatelError("malloc is not work\n");
  S->next = NULL;
  S->data = -1;
  return S;
}


int isEmpty(Stack stack)
{
  return stack->next == NULL;
}


void makeEmpty(Stack stack)
{
  if (isEmpty(stack))
  {
    printf("stack is already a empty stack \n");
    return;
  }
  else
  {
    while(!isEmpty(stack))
      pop(stack);
  }
  
}


void push(Stack stack, elementType data)
{
  Node N = (Node)malloc(sizeof(Node));
  N->data = data;
  N->next = stack->next;
  stack->next = N;
}


elementType top(Stack stack)
{
  if(!isEmpty(stack))
    return stack->next->data;
  else
    fatelError("stack is empty! \n");
    return 0;
}


elementType pop(Stack stack)
{
  if (!isEmpty(stack))
  {
    Node popedNode = stack->next;
    elementType popedVar = popedNode->data;
    stack->next = popedNode->next;
    free(popedNode);
    return popedVar;
  }
  else
  {
    fatelError("stack is empty! \n");
    return -1;
  }
}


// 这个函数的作用是?
void disposeStack(Stack stack)
{

}

my_stack_test.c

#include "my_stack.c"


int main()
{
  Stack stack = createStack();
  for(int i = 0; i < 10; i++)
  {
    push(stack, (i*i+1)*2);
    printf("push %d \n", (i*i+1)*2);
  }
  
  // makeEmpty(stack);

  for(int i = 0; i < 10; i++)
    printf("pop %d \n", pop(stack));
  
  return EXIT_SUCCESS;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值