Data Structure - List Stack (C)

分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击人工智能教程

/*
 * 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
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值