数据结构与算法分析 P86 Stack 栈的实现

链表实现Stack


stack.h 

#pragma once

#include <iostream>
#include <stdbool.h>

struct Node;
typedef struct Node *PtrToNode;
typedef PtrToNode Stack;
typedef int ElementType;

bool IsEmpty(Stack S);
Stack CreateStack();
void DisposeStack(Stack S);         // 删除栈(把top指针也删除)
void MakeEmpty(Stack S);            // 清空栈
void Push(ElementType X, Stack S);
ElementType Top(Stack S);
void Pop(Stack S);
ElementType TopAndPop(Stack S);


stack.cpp

#include "Stack.h"
#include <stdlib.h>

struct Node
{
	ElementType Element;
	PtrToNode Next;
};

bool IsEmpty(Stack S)
{
	return S->Next == NULL;
}

Stack CreateStack()
{
	Stack S = (Stack)malloc(sizeof(struct Node));
	if (S == NULL)
		std::cout<<"Out of space!"<<std::endl;
	S->Next = NULL;
	return S;
}

void DisposeStack(Stack S)
{
	MakeEmpty(S);
	free(S);
}

void MakeEmpty(Stack S)
{
	if (S == NULL)
		std::cout << "Must use CreateStack first!" << std::endl;
	else
		while (!IsEmpty(S))
			Pop(S);
}

void Push(ElementType X, Stack S)
{
	PtrToNode TmpCell = (PtrToNode)malloc(sizeof(struct Node));
	if (TmpCell == NULL)
		std::cout<<"Out of space!"<<std::endl;
	TmpCell->Element = X;
	TmpCell->Next = S->Next;
	S->Next = TmpCell;
}

ElementType Top(Stack S)
{
	if (IsEmpty(S))
		std::cout << "Empty Stack!" << std::endl;
	return S->Next->Element;
}

void Pop(Stack S)
{
	if (!IsEmpty(S))
	{
		PtrToNode TmpCell = S->Next;
		S->Next = TmpCell->Next;
		free(TmpCell);
	}
	else
		std::cout << "Empty stack!" << std::endl;
}

ElementType TopAndPop(Stack S)
{
	if (!IsEmpty(S))
	{
		PtrToNode TmpCell = S->Next;
		ElementType Element = TmpCell->Element;
		S->Next = TmpCell->Next;
		free(TmpCell);
		return Element;
	}
	else
		std::cout<<"Empty stack!"<<std::endl;
}

main.c 

#include <stdio.h>
#include "stack.h"

using namespace std;
int main()
{
	Stack S;

	S = CreateStack();
	for (int i = 0; i < 10; i++)
		Push(i, S);

	TopAndPop(S);            //抛出顶部的9
	
	while (!IsEmpty(S))
	{
		printf("%d\n", Top(S));
		Pop(S);
	}

	DisposeStack(S);
	
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值