栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

使用C语言实现的栈

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用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
#include


// 打印错误消息并退出程序
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 workn");
  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;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/429972.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号