用链表实现栈

用一般链表创建的逆向思维就可以。一般链表创建是新建一个节点作为已有节点的后续节点,而这里是新建一个节点作为已有节点的前驱节点。所以最新创建的节点在链表开头,即栈顶位置。

注意Push、Pop和DeleteStack都会改变栈顶指针,所以必须传引用

StackByList.h

#ifndef _STACK_H

typedef struct StackByList* PtrStackByList;
typedef struct StackByList* TopOfStackByList;

void Push(int X, TopOfStackByList &S);
int Pop(TopOfStackByList &S);
int Top(TopOfStackByList S);
bool IsEmpty(TopOfStackByList S);
void DeleteStack(TopOfStackByList &S);

#endif

struct StackByList
{
	int m_value;
	PtrStackByList m_next;
};

StackByList.cpp

#include "StdAfx.h"
#include "StackByList.h"

void Push(int X, TopOfStackByList &S)
{
	PtrStackByList P = NULL;
	P = new StackByList();
	P->m_value = X;
	P->m_next = S;
	S = P;
}

int Pop(TopOfStackByList &S)
{
	if (S == NULL)
		throw "Empty stack!";

	int top = 0;
	top = S->m_value;
	PtrStackByList P = S->m_next;
	delete S;
	S = P;

	return top;
}

int Top(TopOfStackByList S)
{
	if (S == NULL)
		throw "Empty stack!";

	return S->m_value;
}

bool IsEmpty(TopOfStackByList S)
{
	if (S == NULL)
		return true;
	else
		return false;
}

void DeleteStack(TopOfStackByList &S)
{
	while (S)
		Pop(S);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值