数据结构·栈与队列介绍与实现

目录

栈的概念及结构

概念选择题 

栈的实现

Stack.h

Stack.c

Test.c

一道关于栈的oj题目

 20. 有效的括号

描述

解答代码

队列的概念及结构

队列的实现 

Queue.h

Queue.c

Test.c

结束语


栈的概念及结构

栈:一种特殊的线性表,其只允许在固定的一端进行插入和删除元素操作。
        进行数据插入和删除操作的一端称为栈顶,另一端称为栈底。
        栈中的数据元素遵守后进先出LIFO Last In First Out )的原则。
压栈:栈的插入操作叫做进栈 / 压栈 / 入栈, 入数据在栈顶
出栈:栈的删除操作叫做出栈。 出数据也在栈顶

 

栈的实现一般可以使用 数组或者链表实现 ,相对而言数组的结构实现更优一些。因为数组在尾上插入数据的代价比较小。

概念选择题 

答案 -- 选中查看

1、B

2、C

栈的实现

Stack.h

#pragma once

#include<stdio.h>

#include<assert.h>
#include<stdbool.h>
#include<stdlib.h>

//静态不考虑
//#define N 100
//typedef int STDataType;
//struct Stack
//{
//	STDataType a[N];
//	int top;
//};


typedef int STDataType;
typedef struct Stack
{
	STDataType* a;
	int top;		//数据
	int capacity;	//空间容量
}ST;

//初始化
void StackInit(ST* ps);

//销毁
void StackDestroy(ST* ps);

//入栈
void StackPush(ST* ps , STDataType x);	//根据栈的概念 栈只有一个地方可以插入

//出栈
void StackPop(ST* ps);

//访问Top位置
STDataType StackTop(ST* ps);

//检查是否为空
bool StackEmpty(ST* ps);

//查看数据数量
int StackSize(ST* ps);	//调用函数来实现 -- 数据结构建议不要直接访问结构数据,一定要通过函数接口访问
						//解耦 -- 高内聚,低耦合

Stack.c

#include "Stack.h"

//初始化
void StackInit(ST* ps)
{
	assert(ps);
	ps->a = NULL;
	ps->capacity = ps->top = 0;
}

//销毁
void StackDestroy(ST* ps)
{
	assert(ps);

	free(ps->a);
	ps->a = NULL;
	ps->capacity = ps->top = 0;
}

//入栈
void StackPush(ST* ps, STDataType x)
{
	assert(ps);
	//扩容
	if (ps->top == ps->capacity)	//根据初始化的内容来判断
	{
		int newCapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
		STDataType* tmp = (STDataType*)realloc(ps->a, sizeof(STDataType) * newCapacity);
		if (tmp == NULL)
		{
			perror("realloc fail");
			exit(-1);
		}
		ps->a = tmp;
		ps->capacity = newCapacity;
	}


	ps->a[ps->top] = x;
	ps->top++;

}

//出栈
void StackPop(ST* ps)
{
	assert(ps);
	assert(!StackEmpty(ps));

	--ps->top;
}

//访问Top位置
STDataType StackTop(ST* ps)
{
	assert(ps);
	assert(!StackEmpty(ps));

	return ps->a[ps->top - 1];
}

//检查是否为空
bool StackEmpty(ST* ps)
{
	assert(ps);

	return ps->top == 0;
}

//查看数据数量
int StackSize(ST* ps)
{
	assert(ps);

	return ps->top; //这里的top刚好是数据的下一个位置,自然就是数据个数
}

Test.c

#include "Stack.h"


void TestStack()
{
	ST st;
	StackInit(&st);
	StackPush(&st, 1);
	StackPush(&st, 2);
	StackPush(&st, 3);
	printf("%d ", StackTop(&st));
	StackPop(&st);
	printf("%d ", StackTop(&st));	
	StackPop(&st);


	StackPush(&st, 4);
	StackPush(&st, 5);
	
	while (!StackEmpty(&st))
	{
		printf("%d ", StackTop(&st));	//访问栈顶数据
		StackPop(&st);	//根据栈的性质,访问一个弹出一个
	}
	printf("\n");
}


int main()
{
	TestStack();

	return 0;
}

一道关于栈的oj题目

 20. 有效的括号

给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/valid-parentheses

示例 1:

输入:s = "( )"
输出:true
示例 2:

输入:s = "( )[ ]{ }"
输出:true
示例 3:

输入:s = "( ]"
输出:false
示例 4:

输入:s = "( [ ) ]"
输出:false
示例 5:

输入:s = "{ [ ] }"
输出:true

提示:

  • 1 <= s.length <= 104
  • s 仅由括号 '()[]{}' 组成

描述

C没有栈的,要用C解决只可以自己写个栈解决

解答代码

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

typedef int STDataType;
typedef struct Stack
{
	STDataType* a;
	int top;		//数据
	int capacity;	//空间容量
}ST;

//初始化
void StackInit(ST* ps);

//销毁
void StackDestroy(ST* ps);

//入栈
void StackPush(ST* ps , STDataType x);	//根据栈的概念 栈只有一个地方可以插入

//出栈
void StackPop(ST* ps);

//访问Top位置
STDataType StackTop(ST* ps);

//检查是否为空
bool StackEmpty(ST* ps);

//查看数据数量
int StackSize(ST* ps);	//调用函数来实现 -- 数据结构建议不要直接访问结构数据,一定要通过函数接口访问
						//解耦 -- 高内聚,低耦合


//初始化
void StackInit(ST* ps)
{
	assert(ps);
	ps->a = NULL;
	ps->capacity = ps->top = 0;
}

//销毁
void StackDestroy(ST* ps)
{
	assert(ps);

	free(ps->a);
	ps->a = NULL;
	ps->capacity = ps->top = 0;
}

//入栈
void StackPush(ST* ps, STDataType x)
{
	assert(ps);
	//扩容
	if (ps->top == ps->capacity)	//根据初始化的内容来判断
	{
		int newCapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
		STDataType* tmp = (STDataType*)realloc(ps->a, sizeof(STDataType) * newCapacity);
		if (tmp == NULL)
		{
			perror("realloc fail");
			exit(-1);
		}
		ps->a = tmp;
		ps->capacity = newCapacity;
	}


	ps->a[ps->top] = x;
	ps->top++;

}

//出栈
void StackPop(ST* ps)
{
	assert(ps);
	assert(!StackEmpty(ps));

	--ps->top;
}

//访问Top位置
STDataType StackTop(ST* ps)
{
	assert(ps);
	assert(!StackEmpty(ps));

	return ps->a[ps->top - 1];
}

//检查是否为空
bool StackEmpty(ST* ps)
{
	assert(ps);
	return ps->top == 0;
}

//查看数据数量
int StackSize(ST* ps)
{
	assert(ps);

	return ps->top; //这里的top刚好是数据的下一个位置,自然就是数据个数
}



bool isValid(char * s){


    ST st;
    StackInit(&st);
    while(*s)
    {
        if(*s == '{' || *s == '[' || *s == '(')
        {
            StackPush(&st, *s);
        }
        else
        {
            if(StackEmpty(&st)) //如果栈为空就说明一定不匹配 -- 数量不匹配
            {
                StackDestroy(&st);  //销毁空间
                return false;
            }

            char top = StackTop(&st);//保存Top 数据 再弹出来
            StackPop(&st);  //记得弹出来Top
            if((*s == '}' && top != '{')
            || (*s == ']' && top != '[')
            || (*s == ')' && top != '('))
            {
                StackDestroy(&st);  //销毁空间
                return false;
            }   
        }

        ++s;
    }
    //栈不为空 -- 但是数量还是不匹配,只有左括号 -- 这也是不匹配
    bool flag = StackEmpty(&st);
    StackDestroy(&st);  //销毁空间

    return flag;
}

把上面写的栈搬了过来

队列的概念及结构

队列:只允许在一端进行插入数据操作,在另一端进行删除数据操作的特殊线性表,队列具有 先进先出 FIFO(First In First Out)
入队列:进行插入操作的一端称为 队尾
出队列:进行删除操作的一端称为 队头

 

队列一般体现公平性 -- 比如在银行中的排队,先排队先办理,即先进先出,出于这点,使用链表更适合实现

队列的实现 

Queue.h

#pragma once

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

//能用单链表解决问题就可以用单链表 -- 没必要使用双向循环链表,这属于有点小题大做了

typedef int QDataType;
typedef struct QueueNode
{
	struct QueueNode* next;
	QDataType data;
}QNode;

//再定义一个节点来存放两个指针,方便后面操作
typedef struct Queue
{
	//尾指针
	QNode* tail;
	//头指针
	QNode* head;
	int size;
}Queue;

//初始化  -- 到现在有三种不用二级指针来初始化结构体了 返回值、哨兵位的头节点和这里的创立一个新的结构体放俩这种
void QueueInit(Queue* pq);

//销毁
void QueueDestroy(Queue* pq);

//入队列 -- 根据队列的性质 只尾插
void QueuePush(Queue* pq,QDataType x);

//出队列 -- 根据队列的性质 只头删
void QueuePop(Queue* pq);

//查看头
QDataType QueueFront(Queue* pq);

//查看尾
QDataType QueueBack(Queue* pq);

//判断是否为空
bool QueueEmpty(Queue* pq);

//查看节点长度
int QueueSize(Queue* pq);

Queue.c

#include "Queue.h"

//初始化  -- 到现在有三种不用二级指针来初始化结构体了 返回值、头节点
void QueueInit(Queue* pq)
{
	assert(pq);	//因为这里是自己创立的节点是不可能为空的,为空就是出问题了
	pq->head = pq->tail = NULL;
	pq->size = 0;
}

//销毁
void QueueDestroy(Queue* pq)
{
	assert(pq);
	QNode* cur = pq->head;
	while (cur)
	{
		QNode* del = cur;
		cur = cur->next;
		free(del);
	}

	pq->head = pq->tail = NULL;	//要改变什么就需要什么的指针,这里置空就可以了
}

//入队列 -- 根据队列的性质 只尾插
void QueuePush(Queue* pq, QDataType x)
{
	assert(pq);
	QNode* newnode = (QNode*)malloc(sizeof(QNode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		exit(-1);
	}
	else
	{
		newnode->data = x;
		newnode->next = NULL;	//这里置空,下面就不需要置空了
	}

	if (pq->tail == NULL)
	{
		pq->head = pq->tail = newnode;
	}
	else
	{
		pq->tail->next = newnode;
		pq->tail = newnode;
	}

	pq->size++;
}

//出队列 -- 根据队列的性质 只头删
void QueuePop(Queue* pq)
{
	assert(pq);
	assert(!QueueEmpty(pq));

	if (pq->head->next == NULL)	//防止只剩下一个节点时候再删,就会导致野指针
	{
		free(pq->head);
		pq->tail = pq->head = NULL;
	}
	else
	{
		QNode* del = pq->head;
		pq->head = pq->head->next;

		free(del);
		del = NULL;
	}

	pq->size--;
}

//查看头
QDataType QueueFront(Queue* pq)
{
	assert(pq);
	assert(!QueueEmpty(pq));

	return pq->head->data;
}

//查看尾
QDataType QueueBack(Queue* pq)
{
	assert(pq);
	assert(!QueueEmpty(pq));

	return pq->tail->data;
}

//判断是否为空
bool QueueEmpty(Queue* pq)
{
	assert(pq);

	return pq->head == NULL && pq->tail == NULL; //理论上两个都应该为空才为空,一般一个为空就都会为空,不是就出问题了
}

//查看节点长度
int QueueSize(Queue* pq)
{
	assert(pq);

	//这样写就变为O(N)级别了 为此需要稍作修改
	//QNode* cur = pq->head;
	//int n = 0;
	//while (cur)
	//{
	//	++n;
	//	cur = cur->next;
	//}

	//return n;

	return pq->size;
}

Test.c

#include "Queue.h"

void TestQueue()
{
	Queue q; //这里创立了一个节点,使用不会为空
	//初始化
	QueueInit(&q);
	QueuePush(&q, 1);
	QueuePush(&q, 2);

	printf("%d ", QueueFront(&q));
	QueuePop(&q);
	//打印尾部
	printf("%d ", QueueFront(&q));

	QueuePush(&q, 3);
	QueuePush(&q, 4);

	
	while (!QueueEmpty(&q))
	{
		printf("%d ", QueueFront(&q));
		QueuePop(&q);
	}

	printf("\nsize =%d \n",QueueSize(&q));

	QueueDestroy(&q);
}


int main()
{

	TestQueue();

	return 0;
}

结束语

枝上柳绵吹又少,天涯何处无芳草。
                                                        宋·苏轼 《蝶恋花·春景》 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

清风玉骨

爱了!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值