数据结构:栈、链栈

1 篇文章 0 订阅
1 篇文章 0 订阅

      

        栈的插入和删除只在栈顶进行操作,在单链表中,头指针是单链表的必须元素;而在栈中,栈顶指针也是链栈的必须元素,且一般将栈顶放在单链表的头部。 

        线性表有顺序存储结构和链式存储结构,栈属于线性表的一种,也具有顺序存储结构和链式存储结构。对于栈的链式存储结构,一般称之为链栈。

栈的特点:先进后出

栈函数实现:

1.初始化

2.判满

3.压栈

4.判空

5.出栈

6.带元素出栈

7.清栈

#include<stdio.h>
#include<stdlib.h>

#define MAXSIZE 10
typedef int ELEM_TYPE;

typedef struct Stack
{
	ELEM_TYPE data[MAXSIZE];
	int top;
}Stack;

//pst没有判断NULL情况
void Init(Stack* pst)
{
	pst->top = 0;
}
bool IsFull(Stack* pst)
{
	return pst->top == MAXSIZE;
}
bool Push(Stack* pst,ELEM_TYPE val)
{
	bool rt = false;
	if (!IsFull(pst))
	{
		pst->data[pst->top++] = val;
		rt = true;
	}
	return rt;
}
bool IsEmpty(Stack* pst)
{
	return pst->top == 0;
}
bool Pop(Stack* pst)
{
	bool rt = false;
	if (!IsEmpty(pst))
	{
		pst->top--;
		rt = true;
	}
	return rt;
}

//带出元素
//bool Pop(Stack* pst, ELEM_TYPE* prt)
//{
//	if (IsEmpty(pst))
//	{
//		return false;
//	}
//	*prt = pst->data[pst->top - 1];
//	pst->top--;
//	return true;
//}

ELEM_TYPE Top(Stack* pst)
{
	if (IsEmpty(pst))
	{
		throw exception("stack is empty!");
	}
	return pst->data[pst->top - 1];
}
void Clear(Stack* pst)
{
	pst->top = 0;
}
void Destroyed(Stack* pst)
{
	Clear(pst);
}

 

链栈函数实现:

1.初始化

2.压栈

3.判空

4.出栈

5.带元素出栈

6.清栈

#include<stdio.h>
#include<stdlib.h>

typedef int ELEM_TYPE;

typedef struct Node
{
	ELEM_TYPE mdata;
	struct Node* pnext;
}Node;
typedef struct Stack
{
	Node head;
}Stack;

void Init(Stack* pst)
{
	(pst->head).pnext = NULL;
}


Node* BuyNode(ELEM_TYPE val)
{
//	Node* pnewnode = (Node*)malloc(sizeof(Node));
	Node* pnewnode = new Node();
	if (pnewnode != NULL)
	{
		pnewnode->pnext = NULL;
		pnewnode->mdata = val;
	}
	return pnewnode;
}
bool Push(Stack* pst, ELEM_TYPE val)
{
	Node* pnewnode = BuyNode(val);
	if (pnewnode == NULL)
	{
		return false;
	}
	pnewnode->pnext = (pst->head).pnext;
	(pst->head).pnext = pnewnode;
	return true;
}


bool IsEmpty(Stack* pst)
{
	return (pst->head).pnext == NULL;
}
//不带出元素
bool Pop(Stack* pst)
{
	if (IsEmpty(pst))
	{
		return false;
	}
	Node* pCur = (pst->head).pnext;
	(pst->head).pnext = pCur->pnext;
	free(pCur);
	return true;
}

//带出元素
bool Pop(Stack* pst, ELEM_TYPE* prt)
{
	if (IsEmpty(pst))
	{
		return false;
	}
	Node* pCur = (pst->head).pnext;
	(pst->head).pnext = pCur->pnext;

	*prt = pCur->mdata;
	free(pCur);
	return true;
}

ELEM_TYPE Top(Stack* pst)
{
	if (IsEmpty(pst))
	{
		throw exception("Stack is Empty!");
	}
	return ((pst->head).pnext)->mdata;
}

void Clear(Stack* pst)
{
	Node* pCur = (pst->head).pnext;
	Node* pNext = pCur;

	while (pCur != NULL)
	{
		pNext = pCur->pnext;
		free(pCur);
		pCur = pNext;
	}
	(pst->head).pnext = NULL;
}
void Destroyed(Stack* pst)
{
	Clear(pst);
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值