Data Structure - List Stack (C)
分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击http://www.captainbed.net
/*
* Fatal.h - by FreeMan
*/
#include <stdio.h>
#include <stdlib.h>
#define Error( Str ) FatalError( Str )
#define FatalError( Str ) fprintf( stderr, "%s\n", Str ), exit( 1 )
/*
* LiStack.h - by FreeMan
*/
typedef int ElementType;
#ifndef _LiStack_H_
#define _LiStack_H_
struct LiStackNode;
typedef struct LiStackNode *PtrToNode;
typedef PtrToNode LiStack;
int IsLiStackEmpty(LiStack S);
LiStack CreateLiStack(void);
void DisposeLiStack(LiStack S);
void MakeLiStackEmpty(LiStack S);
void PushLiStack(ElementType X, LiStack S);
ElementType TopOfLiStack(LiStack S);
void PopLiStack(LiStack S);
#endif
/*
* LiStack.c - by FreeMan
*/
#include "LiStack.h"
#include "..\Fatal.h"
#include <stdlib.h>
struct LiStackNode
{
ElementType Element;
PtrToNode Next;
};
int IsLiStackEmpty(LiStack S)
{
return S->Next == NULL;
}
LiStack CreateLiStack(void)
{
LiStack S;
S = malloc(sizeof(struct LiStackNode));
if (S == NULL)
{
FatalError("Out of memory!!");
}
S->Next = NULL;
MakeLiStackEmpty(S);
return S;
}
void MakeLiStackEmpty(LiStack S)
{
if (S == NULL)
{
Error("Must use CreateLiStack first!");
}
else
{
while (!IsLiStackEmpty(S))
{
PopLiStack(S);
}
}
}
void DisposeLiStack(LiStack S)
{
MakeLiStackEmpty(S);
free(S);
}
void PushLiStack(ElementType X, LiStack S)
{
PtrToNode TmpCell;
TmpCell = malloc(sizeof(struct LiStackNode));
if (TmpCell == NULL)
{
FatalError("Out of memory!!");
}
else
{
TmpCell->Element = X;
TmpCell->Next = S->Next;
S->Next = TmpCell;
}
}
ElementType TopOfLiStack(LiStack S)
{
if (!IsLiStackEmpty(S))
{
return S->Next->Element;
}
Error("Empty stack!");
return 0; /* Return value used to avoid warning */
}
void PopLiStack(LiStack S)
{
PtrToNode FirstCell;
if (IsLiStackEmpty(S))
{
Error("Empty stack!");
}
else
{
FirstCell = S->Next;
S->Next = S->Next->Next;
free(FirstCell);
}
}
/*
* LiStackTest.c - by FreeMan
*/
#include "LiStack.h"
#include <stdio.h>
main()
{
LiStack S;
int i;
S = CreateLiStack();
for (i = 0; i < 10; i++)
{
PushLiStack(i, S);
}
while (!IsLiStackEmpty(S))
{
printf("%d\n", TopOfLiStack(S));
PopLiStack(S);
}
DisposeLiStack(S);
return 0;
}
// Output:
/*
9
8
7
6
5
4
3
2
1
0
*/
还没有评论,来说两句吧...