使用链表实现
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;
}