分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击人工智能教程
/*
* Fatal.h - by LiveEveryDay
*/
#include <stdio.h>
#include <stdlib.h>
#define Error( Str ) FatalError( Str )
#define FatalError( Str ) fprintf( stderr, "%s\n", Str ), exit( 1 )
/*
* ListStack.h - by LiveEveryDay
*/
typedef int ElementType;
#ifndef _ListStack_
#define _ListStack_
struct ListStackNode;
typedef struct ListStackNode* PtrToNode;
typedef PtrToNode ListStack;
ListStack CreateListStack(void);
void PushListStack(ElementType X, ListStack S);
ElementType TopOfListStack(ListStack S);
void PopListStack(ListStack S);
int IsListStackEmpty(ListStack S);
void MakeListStackEmpty(ListStack S);
void DisposeListStack(ListStack S);
#endif
/*
* ListStack.c - by LiveEveryDay
*/
#include "ListStack.h"
#include "../Fatal.h"
#include <stdlib.h>
struct ListStackNode
{
ElementType Element;
PtrToNode Next;
};
ListStack CreateListStack(void)
{
ListStack S;
S = malloc(sizeof(struct ListStackNode));
if (S == NULL)
{
FatalError("Out of memory!!");
}
S->Next = NULL;
MakeListStackEmpty(S);
return S;
}
void PushListStack(ElementType X, ListStack S)
{
PtrToNode Tmp;
Tmp = malloc(sizeof(struct ListStackNode));
if (Tmp == NULL)
{
FatalError("Out of memory!!");
}
else
{
Tmp->Element = X;
Tmp->Next = S->Next;
S->Next = Tmp;
}
}
ElementType TopOfListStack(ListStack S)
{
if (!IsListStackEmpty(S))
{
return S->Next->Element;
}
Error("Empty stack!");
return 0; /* Return value used to avoid warning */
}
void PopListStack(ListStack S)
{
PtrToNode FirstCell;
if (IsListStackEmpty(S))
{
Error("Empty stack!");
}
else
{
FirstCell = S->Next;
S->Next = S->Next->Next;
free(FirstCell);
}
}
int IsListStackEmpty(ListStack S)
{
return S->Next == NULL;
}
void MakeListStackEmpty(ListStack S)
{
if (S == NULL)
{
Error("Must use CreateListStack first!");
}
else
{
while (!IsListStackEmpty(S))
{
PopListStack(S);
}
}
}
void DisposeListStack(ListStack S)
{
MakeListStackEmpty(S);
free(S);
}
/*
* ListStackTest.c - by LiveEveryDay
*/
#include "ListStack.h"
#include <stdio.h>
int main(void)
{
printf("Testing List Stack...\n");
ListStack S;
int i;
S = CreateListStack();
for (i = 0; i < 10; i++)
{
PushListStack(i, S);
}
while (!IsListStackEmpty(S))
{
printf("%d\n", TopOfListStack(S));
PopListStack(S);
}
DisposeListStack(S);
return 0;
}
// Output:
/*
9
8
7
6
5
4
3
2
1
0
*/