数据结构 || 栈与队列

本文详细介绍了栈和队列这两种基本数据结构,包括顺序栈和链栈的概念,以及进栈出栈的变化形式。同时,文章还探讨了循环队列和链队列的实现。此外,通过7个典型习题,如递归、使用两个栈实现队列、使用两个队列实现栈等,展示了栈和队列在实际问题中的应用,如删除字符串中相邻重复项、有效括号判断、逆波兰表达式解析等。
摘要由CSDN通过智能技术生成


栈和队列都是线性结构(线性表),特殊性在于栈与队列的 基本操作是线性表操作的子集,是操作受限的线性表,称为限定性的数据结构。

线性表
逻辑结构:一对一 逻辑结构:一对一
存储结构:顺序表、链表 存储结构:顺序栈、链栈
运算规则:随机存取 运算规则:先进后出LIFO

栈:stack

先进后出的线性表

  1. 定义:限定仅在表尾进行插入或删除操作的线性表,表尾称为栈顶,表头称为栈底,不含元素的空表称为空栈。
    在这里插入图片描述

顺序栈

顺序栈,即栈的顺序存储结构是利用一组地址连续的存储单元一次存放自栈底到栈顶的数据元素,同时设置指针top指示栈顶元素在顺序栈中的位置
top指针的位置是没有数据元素

在这里插入图片描述

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<iostream>
#include<assert.h>
#define SIZE  100
#define TRUE 1
#define OK 1
#define ERROR 0
#define OVERFLOW -2    //超出
#define FALSE 0
#define INCSIZE 2
#define NULLPTR -3
typedef int ElemType;
typedef int Status;    //状态
using namespace std;

class SeqStack   //只能从尾部插入删除
{
   
private:
	ElemType* top;   //栈顶指针
	ElemType* base;  //栈底指针
	int stacksize;   //容量
public:
	SeqStack()
	{
   
		cout << "SeqStack()" << endl;
		base = (ElemType*)malloc(sizeof(ElemType) * SIZE);
		if (NULL == base) return ;
		top = base;
		stacksize = SIZE;
	}
	~SeqStack()
	{
   
		cout << "~SeqStack()" << endl;
		free(base);
		base = NULL;
		top = NULL;
		stacksize = 0;
	}
	void Clear() //所有数据元素
	{
   
		top = base;
	}

	bool IsEmpty()
	{
   
		return GetSize() == 0;    //return top == base;
	}
	bool IsFull()
	{
   
		return GetSize() == SIZE;
	}
	int GetSize()
	{
   
		return (ElemType)(top - base);    //算头不算尾
	}
	Status Push(ElemType val)
	{
    
		if (IsFull() && !IncSize())
		{
   
			return ERROR;
		}
		*top = val;
		top+=1;
		return OK;
	}
	bool IncSize()           //满-》扩容
	{
   
		int total = stacksize * INCSIZE;
		ElemType* newdata = (ElemType*)realloc(base, total);
		if (NULL == newdata)
		{
   
			return FALSE;
		}
		base = newdata;
		top = base + stacksize;
		return TRUE;
	}
	Status Pop(ElemType* p)          //取出数据并删除
	{
   
		if (IsEmpty())
		{
   
			return ERROR;
		}
		if (p == NULL)return NULLPTR;
		*p = *(top-1);        //top指向的位置没有数据 所以要取它下一个位置的数据
		top-=1;               
		return OK;
	}
	Status GetTop(ElemType* p)             //只取栈顶数据不删除
	{
   
		if (IsEmpty())
		{
   
			return ERROR;
		}
		if (p == NULL)return NULLPTR;
	    *p = *(top-1);
		return OK;
	}
};

int main()
{
   
	SeqStack s;
	int a;
	ElemType val;
	for (int i = 0; i < 5; i++)
	{
   
		cin >> a; 
		s.Push(a);
	}
	while (!s.IsEmpty())
	{
   
		s.Pop(&val);
		cout << val << endl;
	}
	return 0;
}

链栈

在这里插入图片描述

typedef struct StackNode
{
   
	ElemType data;
	StackNode* next;
}StackNode,*PStackNode;
class LinkStack
{
   
private:
	StackNode* top;
	int cursize;
public :
	LinkStack()
	{
   
		top = BuyNode();
		
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值