electricperi 2014-08-06
栈(C语言实现,基于链式结构)
Stack.h文件
/**
* 栈(C语言实现,基于链式结构)
* 指定数据类型为整型
*/
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
typedef int Status;
typedef int ElemType;
//定义栈节点的结构
typedef struct StackNode{
ElemType data;
struct StackNode* next;
}StackNode;
//定义栈的结构
typedef struct Stack{
StackNode* top;
int count;
}Stack;
/*
* 初始化一个空栈
*/
Status InitStack(Stack* s);
/*
* 销毁栈
*/
Status DestroyStack(Stack* s);
/*
* 清空栈
*/
Status ClearStack(Stack* s);
/*
* 判断栈是否为空
*/
Status StackEmpty(Stack s);
/*
* 获取栈的长度
*/
int StackLength(Stack s);
/*
* 获取栈顶元素
*/
Status GetTop(Stack s, ElemType* e);
/*
* 将元素压入栈
*/
Status Push(Stack* s, ElemType e);
/*
* 将元素弹出栈
*/
Status Pop(Stack* s, ElemType* e);
/*
* 打印栈
*/
void PrintStack(Stack* s);
Stack.c文件
#include <stdio.h>
#include <stdlib.h>
#include "Stack.h"
Status InitStack(Stack* s)
{
s->top = NULL;
s->count = 0;
return OK;
}
Status DestroyStack(Stack* s)
{
StackNode* sn_tmp_ptr;
while(s->top){
sn_tmp_ptr = s->top;
s->top = s->top->next;
free(sn_tmp_ptr);
}
free(s);
}
Status ClearStack(Stack* s)
{
while(s->top){
s->top->data = 0;
s->top = s->top->next;
}
}
Status StackEmpty(Stack s)
{
return s.count<1 ? TRUE : FALSE;
}
int StackLength(Stack s)
{
return s.count;
}
Status GetTop(Stack s, ElemType* e)
{
*e = s.top->data;
return OK;
}
Status Push(Stack* s, ElemType e)
{
StackNode* snptr = (StackNode*)malloc(sizeof(StackNode));
snptr->data = e;
snptr->next = s->top;
s->top = snptr;
s->count++;
return OK;
}
Status Pop(Stack* s, ElemType* e)
{
*e = s->top->data;
StackNode* sn_tmp_ptr = s->top;
s->top = s->top->next;
s->count--;
free(sn_tmp_ptr);
return OK;
}
void PrintStack(Stack* s)
{
while(s->top){
printf("%d\n",s->top->data);
s->top = s->top->next;
}
}
int main()
{
Stack s;
ElemType e_tmp;
InitStack(&s);
printf("Is Stack empty : %d\n",StackEmpty(s));
Push(&s, 3);
Push(&s, 2);
Push(&s, 1);
Push(&s, 0);
Pop(&s, &e_tmp);
Pop(&s, &e_tmp);
printf("Is Stack empty : %d\n",StackEmpty(s));
PrintStack(&s);
printf("%d",s.count);
}
将C语言梳理一下,分布在以下10个章节中: