数据结构~~栈和队列

简介: 在计算机科学中,数据结构是构建高效程序的基础。栈和队列是两种重要且常用的线性数据结构,它们在解决各种问题中发挥着关键作用。

一、基本概念


计算机科学中,数据结构是构建高效程序的基础。栈和队列是两种重要且常用的线性数据结构,它们在解决各种问题中发挥着关键作用。

栈的概念

栈:一种特殊的线性表,其只允许在固定的一端进行插入和删除元素操作。进行数据插入和删除操作的一端 称为栈顶,另一端称为栈底。栈中的数据元素遵守后进先出LIFO(Last In First Out)的原则。 压栈:栈的插入操作叫做进栈/压栈/入栈,入数据在栈顶。 出栈:栈的删除操作叫做出栈。出数据也在栈顶。栈在许多场景中被广泛应用,比如函数调用的嵌套、表达式求值等。

栈的实现

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

队列的概念

队列:只允许在一端进行插入数据操作,在另一端进行删除数据操作的特殊线性表,队列具有先进先出 FIFO(First In First Out) 入队列:进行插入操作的一端称为队尾 出队列:进行删除操作的一端称为队头。队列常用于任务调度、消息传递等情况。

队列的实现

队列也可以数组和链表的结构实现,使用链表的结构实现更优一些,因为如果使用数组的结构,出队列在数 组头上出数据,效率会比较低。

二、栈


栈的结构

typedef int STDataType;
typedef struct Stack
{
  STDataType* a;
  int top;//栈顶
  int capacity;//栈的总容量
}ST;

1.初始化栈

void STInit(ST* pst)
{
  assert(pst);
  pst->a = NULL;
  pst->top = 0;
  pst->capacity = 0;
}

2.摧毁栈

void STDestroy(ST* pst)
{
  assert(pst);
  free(pst->a);
  pst->a = NULL;
  pst->capacity = pst->top = 0;
}

3.插入数据

void STPush(ST* pst, STDataType x)
{
  if (pst->top == pst->capacity)
  {
    int newCapacity = pst->capacity == 0 ? 4 : pst->capacity * 2;
    STDataType* tmp = (STDataType*)realloc(pst->a, newCapacity * sizeof(STDataType));
    if (tmp == NULL)
    {
      perror("realloc err");
      return;
    }
    pst->a = tmp;
    pst->capacity = newCapacity;
  }
  pst->a[pst->top] = x;
  pst->top++;
}

4.删除数据

void STPop(ST* pst)
{
  assert(pst);
  assert(!STEmpty(pst));
  pst->top--;
}

5.获取栈顶元素

STDataType STTop(ST* pst)
{
  assert(pst);
  assert(!STEmpty(pst));
  return pst->a[pst->top - 1];
}

6.判断栈是否为空

bool STEmpty(ST* pst)
{
  assert(pst);
  return pst->top == 0;
}

7.栈的元素个数

int STSize(ST* pst)
{
  assert(pst);
  return pst->top;
}

三、队列


队列的结构

typedef int QDataType;
typedef struct QueueNode
{
  QDataType data;
  struct QueueNode* next;
}QNode;
 
typedef struct Queue
{
  QNode* phead;
  QNode* ptail;
  int size;
}Queue;

1.初始化队列

void QueueInit(Queue* pq)
{
  assert(pq);
  pq->phead = NULL;
  pq->ptail = NULL;
  pq->size = 0;
}

2.摧毁队列

void QueueDestroy(Queue* pq)
{
  assert(pq);
  QNode* cur = pq->phead;
  while (cur)
  {
    QNode* next = cur->next;
    free(cur);
    cur = next;
  }
  pq->phead = pq->ptail = NULL;
  pq->size = 0;
}

3.插入队列

void QueuePush(Queue* pq, QDataType x)
{
  assert(pq);
  QNode* newnode = (QNode*)malloc(sizeof(QNode));
  if (newnode == NULL)
  {
    perror("malloc err");
    return;
  }
  newnode->data = x;
  newnode->next=NULL;
  if (pq->phead == NULL)
  {
    assert(pq->ptail == NULL);
    pq->phead = pq->ptail= newnode;
  }
  else
  {
    pq->ptail->next = newnode;
    pq->ptail = newnode;
  }
  pq->size++;
}

4.删除队列

void QueuePop(Queue* pq)
{
  assert(pq);
  assert(!QueueEmpty(pq));
  if (pq->phead->next == NULL)
  {
    free(pq->phead);
    pq->phead = pq->ptail = NULL;
  }
  else 
  {
    QNode* next = pq->phead->next;
    free(pq->phead);
    pq->phead = next;
  }
  pq->size--;
}

5.队列头部

QDataType QueueFront(Queue* pq)
{
  assert(pq);
  assert(!QueueEmpty(pq));
  return pq->phead->data;
}

6.队列尾部

QDataType QueueBack(Queue* pq)
{
  assert(pq);
  assert(!QueueEmpty(pq));
  return pq->ptail->data;
}

7.查看队列的总长

bool QueueEmpty(Queue* pq)
{
  assert(pq);
  return pq->phead == NULL
    && pq->ptail == NULL;
}

8.判断队列为不为空

bool QueueEmpty(Queue* pq)
{
  assert(pq);
  return pq->phead == NULL
    && pq->ptail == NULL;
}

四、栈和队列的练习


有效的括号

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

有效字符串需满足:

  1. 左括号必须用相同类型的右括号闭合。
  2. 左括号必须以正确的顺序闭合。
  3. 每个右括号都有一个对应的相同类型的左括号。

示例 1:

输入:s = "()"

输出:true


示例 2:

输入:s = "()[]{}"

输出:true


示例 3:

输入:s = "(]"

输出:false

这题要先创建一个完整的栈,各个接口可以看下面标题五的完整代码


思路:


使用栈来解决这个问题。


遍历字符串中的每个字符:


• 如果遇到左括号('('、'{'、'['),就将其入栈。


• 如果遇到右括号(')'、'}'、']'):


• 检查栈是否为空,如果为空则说明没有对应的左括号,直接返回 false。


• 取出栈顶元素,看是否与当前右括号匹配,如果不匹配则返回 false。


• 遍历完整个字符串后,如果栈为空,说明所有括号都匹配成功,返回 true,否则返回 false。

bool isValid(char* s) {
    ST st;
    STInit(&st);
    while(*s)
    {
        if(*s=='{'||*s=='('||*s=='[')
        {
            STPush(&st,*s);
        }
        else
        {
            if(STEmpty(&st))
            {
                STDestroy(&st);
                return false;
            }
            char top=STTop(&st);
            STPop(&st);
            if((top=='{'&&*s!='}')||(top=='('&&*s!=')')||(top=='['&&*s!=']'))
            {
                STDestroy(&st);
                return false;
            }
        }
        s++;
    }
    bool r =STEmpty(&st);
    STDestroy(&st);
    return r;
}

设计循环队列

设计你的循环队列实现。 循环队列是一种线性数据结构,其操作表现基于 FIFO(先进先出)原则并且队尾被连接在队首之后以形成一个循环。它也被称为“环形缓冲器”。


循环队列的一个好处是我们可以利用这个队列之前用过的空间。在一个普通队列里,一旦一个队列满了,我们就不能插入下一个元素,即使在队列前面仍有空间。但是使用循环队列,我们能使用这些空间去存储新的值。


你的实现应该支持如下操作:


MyCircularQueue(k): 构造器,设置队列长度为 k 。

Front: 从队首获取元素。如果队列为空,返回 -1 。

Rear: 获取队尾元素。如果队列为空,返回 -1 。

enQueue(value): 向循环队列插入一个元素。如果成功插入则返回真。

deQueue(): 从循环队列中删除一个元素。如果成功删除则返回真。

isEmpty(): 检查循环队列是否为空。

isFull(): 检查循环队列是否已满。

思路:


首先,我们需要定义一个类来表示循环队列。这个类需要包含以下几个成员变量:


1. 一个用于存储队列元素的数组。


2. 队列的头部索引和尾部索引。


3. 队列的最大容量。


对于构造器 myCircularQueueCreate(k),我们初始化队列的最大容量为 k,并将头部和尾部索引都初始化为 -1,表示队列是空的。


对于 Front 函数,我们返回头部索引对应的元素,如果队列为空(即头部索引为 -1),则返回 -1。


对于 Rear 函数,我们返回尾部索引对应的元素,如果队列为空(即尾部索引为 -1),则返回 -1。


对于 enQueue(value) 函数,我们首先检查队列是否已满。如果已满,则返回 false。否则,我们将尾部索引向后移动一位(如果尾部索引已经到达数组末尾,则将其设置为 0),并将元素插入到尾部索引对应的位置,然后返回 true。


对于 deQueue() 函数,我们首先检查队列是否为空。如果为空,则返回 false。否则,我们将头部索引向后移动一位(如果头部索引已经到达数组末尾,则将其设置为 0),然后返回 true。


对于 Empty() 函数,我们只需要检查头部索引是否为 -1 即可。


对于 Full() 函数,我们检查尾部索引加 1 后是否等于头部索引(如果尾部索引已经到达数组末尾,则将其设置为 0),如果是,则表示队列已满,否则表示队列未满

typedef struct {
    int* a;
    int head;
    int tail;
    int k;
} MyCircularQueue;
 
 
MyCircularQueue* myCircularQueueCreate(int k) {
    MyCircularQueue* obj=(MyCircularQueue*)malloc(sizeof(MyCircularQueue));
    obj->a=(int*)malloc(sizeof(int)*(k+1));
    obj->head=0;
    obj->tail=0;
    obj->k=k;
    return obj;
}
bool myCircularQueueIsEmpty(MyCircularQueue* obj) {
    return obj->head==obj->tail;
}
 
bool myCircularQueueIsFull(MyCircularQueue* obj) {
    return (obj->tail+1)%(obj->k+1)==obj->head;
}
 
bool myCircularQueueEnQueue(MyCircularQueue* obj, int value) {
    if(myCircularQueueIsFull(obj))
      return false;
    obj->a[obj->tail]=value;
    obj->tail++;
    obj->tail%=(obj->k+1);
    return true;
}
 
bool myCircularQueueDeQueue(MyCircularQueue* obj) {
    if(myCircularQueueIsEmpty(obj))
       return false;
     ++obj->head;
     obj->head%=obj->k+1;
     return true;
 
}
 
int myCircularQueueFront(MyCircularQueue* obj) {
     if(myCircularQueueIsEmpty(obj))
       return -1;
    else
       return obj->a[obj->head];
}
 
int myCircularQueueRear(MyCircularQueue* obj) {
     if(myCircularQueueIsEmpty(obj))
       return -1;
    else
       return obj->a[(obj->tail+obj->k)%(obj->k+1)];
}
 
 
void myCircularQueueFree(MyCircularQueue* obj) {
    free(obj->a);
    free(obj);
}

用栈实现队列

请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):


实现 MyQueue 类:


void push(int x) 将元素 x 推到队列的末尾

int pop() 从队列的开头移除并返回元素

int peek() 返回队列开头的元素

boolean empty() 如果队列为空,返回 true ;否则,返回 false

说明:


你 只能 使用标准的栈操作 —— 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。

你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。

这题要先创建一个完整的栈,各个接口可以看下面标题五的完整代码


思路:


我们可以使用两个栈,一个用于输入(pustst),一个用于输出(popst)。


当进行 push 操作时,直接将元素压入 popst。


当进行 pop 或 peek 操作时,如果 outStack 为空,则将 pustst 中的所有元素依次弹出并压入 popst,然后从 popst进行 pop 或 peek。


这样就能模拟出先入先出的队列行为。

typedef struct {
    ST popst;
    ST pushst;
} MyQueue;
 
 
MyQueue* myQueueCreate() {
    MyQueue* obj=(MyQueue*)malloc(sizeof(MyQueue));
    STInit(&obj->popst);
    STInit(&obj->pushst);
    return obj;
    
}
 
void myQueuePush(MyQueue* obj, int x) {
    STPush(&obj->pushst,x);
}
 
int myQueuePop(MyQueue* obj) {
    int fon = myQueuePeek(obj);
    STPop(&obj->popst);
    return fon;
}
 
int myQueuePeek(MyQueue* obj) {
    if(STEmpty(&obj->popst))
    {
        while(!STEmpty(&obj->pushst))
        {
            int top=STTop(&obj->pushst);
            STPush(&obj->popst,top);
            STPop(&obj->pushst);
        }
    }
    return STTop(&obj->popst);
}
 
bool myQueueEmpty(MyQueue* obj) {
    return STEmpty(&obj->popst)
       &&  STEmpty(&obj->pushst);
}
 
void myQueueFree(MyQueue* obj) {
    //STDestroy(&obj->popst);
    STDestroy(&obj->pushst);
    STDestroy(&obj->popst);
    free(obj);
}

用队列实现栈

请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。


实现 MyStack 类:


void push(int x) 将元素 x 压入栈顶。

int pop() 移除并返回栈顶元素。

int top() 返回栈顶元素。

boolean empty() 如果栈是空的,返回 true ;否则,返回 false 。

注意:


你只能使用队列的标准操作 —— 也就是 push to back、peek/pop from front、size 和 is empty 这些操作。

你所使用的语言也许不支持队列。 你可以使用 list (列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。

这题要先创建一个完整的队列,各个接口可以看下面标题五的完整代码


思路:


当进行 push 操作时,将元素添加到一个非空队列中。


当进行 pop 或 top 操作时,将非空队列中的元素除最后一个外都依次移到另一个空队列中,此时非空队列中的最后一个元素就是栈顶元素,对其进行相应操作后,交换两个队列的角色。


通过这样不断在两个队列之间转移元素来模拟栈的后进先出特性。

typedef struct {
    Queue q1;
    Queue q2;
} MyStack;
 
 
MyStack* myStackCreate() {
    MyStack* pst=(MyStack*)malloc(sizeof(MyStack));
    QueueInit(&pst->q1);
    QueueInit(&pst->q2);
    return pst;
}
 
void myStackPush(MyStack* obj, int x) {
    if(!QueueEmpty(&obj->q1))
    {
        QueuePush(&obj->q1,x);
    }
    else
    {
        QueuePush(&obj->q2,x);
    }
}
 
int myStackPop(MyStack* obj) {
    Queue* empty=&obj->q1;
    Queue* noempty=&obj->q2;
    if(!QueueEmpty(&obj->q1))
    {
        empty=&obj->q2;
        noempty=&obj->q1;
    }
    while(QueueSize(noempty)>1)
    {
        QueuePush(empty,QueueFront(noempty));
        QueuePop(noempty);
    }
    int top =QueueFront(noempty);
    QueuePop(noempty);
    return top;
}
 
int myStackTop(MyStack* obj) {
    if(!QueueEmpty(&obj->q1))
    {
        return QueueBack(&obj->q1);
    }
    else
    {
        return QueueBack(&obj->q2);
    }
}
 
bool myStackEmpty(MyStack* obj) {
    return QueueEmpty(&obj->q1)
        && QueueEmpty(&obj->q2);
}
 
void myStackFree(MyStack* obj) {
    QueueDestroy(&obj->q2);
    QueueDestroy(&obj->q1);
    free(obj);
}

五、完整代码


Stack.h

#pragma once
#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 STInit(ST* pst); //初始化栈
void STDestroy(ST* pst);//摧毁栈
void STPush(ST* pst, STDataType x);//插入数据
void STPop(ST* pst);//删除数据
STDataType STTop(ST* pst);//栈顶 元素
bool STEmpty(ST* pst);//判断 栈是否为空
int STSize(ST* pst);//栈的元素 个数

Stack.c

#include"Stack.h"
void STInit(ST* pst)
{
  assert(pst);
  pst->a = NULL;
  pst->top = 0;
  pst->capacity = 0;
}
void STDestroy(ST* pst)
{
  assert(pst);
  free(pst->a);
  pst->a = NULL;
  pst->capacity = pst->top = 0;
}
void STPush(ST* pst, STDataType x)
{
  if (pst->top == pst->capacity)
  {
    int newCapacity = pst->capacity == 0 ? 4 : pst->capacity * 2;
    STDataType* tmp = (STDataType*)realloc(pst->a, newCapacity * sizeof(STDataType));
    if (tmp == NULL)
    {
      perror("realloc err");
      return;
    }
    pst->a = tmp;
    pst->capacity = newCapacity;
  }
  pst->a[pst->top] = x;
  pst->top++;
}
void STPop(ST* pst)
{
  assert(pst);
  assert(!STEmpty(pst));
  pst->top--;
}
STDataType STTop(ST* pst)
{
  assert(pst);
  assert(!STEmpty(pst));
  return pst->a[pst->top - 1];
}
bool STEmpty(ST* pst)
{
  assert(pst);
  return pst->top == 0;
}
int STSize(ST* pst)
{
  assert(pst);
  return pst->top;
}

队列

Queue.h

#pragma once
#include<stdio.h>
#include<assert.h>
#include<stdbool.h>
#include<stdlib.h>
 
typedef int QDataType;
typedef struct QueueNode
{
  QDataType data;
  struct QueueNode* next;
}QNode;
 
typedef struct Queue
{
  QNode* phead;
  QNode* ptail;
  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);  //队列尾部
int QueueSize(Queue* pq);//查看队列的总长
bool QueueEmpty(Queue* pq);//判断队列为不为空

Queue.c

#include"Queue.h"
void QueueInit(Queue* pq)
{
  assert(pq);
  pq->phead = NULL;
  pq->ptail = NULL;
  pq->size = 0;
}
void QueueDestroy(Queue* pq)
{
  assert(pq);
  QNode* cur = pq->phead;
  while (cur)
  {
    QNode* next = cur->next;
    free(cur);
    cur = next;
  }
  pq->phead = pq->ptail = NULL;
  pq->size = 0;
}
void QueuePush(Queue* pq, QDataType x)
{
  assert(pq);
  QNode* newnode = (QNode*)malloc(sizeof(QNode));
  if (newnode == NULL)
  {
    perror("malloc err");
    return;
  }
  newnode->data = x;
  newnode->next=NULL;
  if (pq->phead == NULL)
  {
    assert(pq->ptail == NULL);
    pq->phead = pq->ptail= newnode;
  }
  else
  {
    pq->ptail->next = newnode;
    pq->ptail = newnode;
  }
  pq->size++;
}
void QueuePop(Queue* pq)
{
  assert(pq);
  assert(!QueueEmpty(pq));
  if (pq->phead->next == NULL)
  {
    free(pq->phead);
    pq->phead = pq->ptail = NULL;
  }
  else 
  {
    QNode* next = pq->phead->next;
    free(pq->phead);
    pq->phead = next;
  }
  pq->size--;
}
QDataType QueueFront(Queue* pq)
{
  assert(pq);
  assert(!QueueEmpty(pq));
  return pq->phead->data;
}
QDataType QueueBack(Queue* pq)
{
  assert(pq);
  assert(!QueueEmpty(pq));
  return pq->ptail->data;
}
int QueueSize(Queue* pq)
{
  assert(pq);
  return pq->size;
}
bool QueueEmpty(Queue* pq)
{
  assert(pq);
  return pq->phead == NULL
    && pq->ptail == NULL;
}

六、总结


栈(Stack)

1. 后进先出原则。


2. 主要操作包括入栈(push)和出栈(pop)。


3. 常用于函数调用、表达式求值、括号匹配等场景。


队列(Queue)


1. 先进先出原则。


2. 主要操作包括入队(enqueue)和出队(dequeue)。


3. 常用于任务调度、排队系统、广度优先搜索等。


两者都是基本的数据结构,具有不同的特点和适用场景,在程序设计中发挥着重要作用。


目录
相关文章
|
4天前
|
存储 算法 调度
数据结构与算法-栈篇
数据结构与算法-栈篇
12 3
|
1天前
数据结构 栈 / 队列(第9天)
数据结构 栈 / 队列(第9天)
|
1天前
|
存储 算法 程序员
【C++进阶】深入STL之 栈与队列:数据结构探索之旅
【C++进阶】深入STL之 栈与队列:数据结构探索之旅
|
1天前
数据结构——栈和队列
数据结构——栈和队列
|
2天前
|
C语言 C++
【数据结构】C语言实现:栈(Stack)与队列(Queue)
【数据结构】C语言实现:栈(Stack)与队列(Queue)
|
4天前
|
算法 调度 Python
数据结构与算法-队列篇
数据结构与算法-队列篇
11 3
|
4天前
数据结构初阶 队列
数据结构初阶 队列
5 0
|
4天前
数据结构初阶 栈
数据结构初阶 栈
8 1
|
9天前
|
算法
数据结构和算法学习记录——栈和队列作业(实现链栈上的进栈、实现链栈上的退栈、实现链队上的入队列)
数据结构和算法学习记录——栈和队列作业(实现链栈上的进栈、实现链栈上的退栈、实现链队上的入队列)
11 0
|
12天前
|
存储 缓存 算法
【数据结构】栈和队列的模拟实现(两个方式实现)
【数据结构】栈和队列的模拟实现(两个方式实现)