返回介绍

二、代码

发布于 2025-02-17 12:55:34 字数 1710 浏览 0 评论 0 收藏 0

//10.1 栈和队列
#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;

/*********栈*****************************/
struct stack
{
  int top;//栈顶指针
  int *s;//数组
  stack(int size):top(0){s = new int[size+1];}
//  ~stack(){delete []s;}
};
void Print(stack S)
{
  int i;
  //从栈底到栈顶的顺序输出
  for(i = 1; i <= S.top; i++)
    cout<<S.s[i]<<' ';
  cout<<endl;
}
//检查一个栈是否为空
bool Stack_Empty(stack &S)
{
  if(S.top == 0)
    return true;
  else
    return false;
}
//入栈
void Push(stack &S, int x)
{
  S.top++;
  S.s[S.top] = x;
}
//出栈
int Pop(stack &S)
{
  if(Stack_Empty(S))
  {
    cout<<"underflow"<<endl;
    exit(0);
  }
  else
  {
    S.top--;
    return S.s[S.top+1];
  }
}
/*********队列****************************/
struct queue
{
  int tail;//队列头指针
  int head;//队列尾指针
  int length;//队列长度
  int *s;//数组
  queue(int size):tail(1),head(1),length(size){s = new int[size+1];}
};
//从队列头到队列尾输出
void Print(queue Q)
{
  int i;
  if(Q.tail >= Q.head)
  {
    for(i = Q.head; i < Q.tail;i++)
      cout<<Q.s[i]<<' ';
    cout<<endl;
  }
  //因为循环的原因,队列尾可能在队列头的前面
  else
  {
    for(i = Q.head; i <= Q.length; i++)
      cout<<Q.s[i]<<' ';
    for(i = 1; i < Q.tail; i++)
      cout<<Q.s[i]<<' ';
    cout<<endl;
  }
}
//判断队列是否为空
bool Queue_Empty(queue Q)
{
  if(Q.tail == Q.head)
    return 1;
  return 0;
}
//入队列
void Enqueue(queue &Q, int x)
{
  Q.s[Q.tail] = x;
  if(Q.tail == Q.length)
    Q.tail = 1;
  else Q.tail++;
}
//出队列
int Dequeue(queue &Q)
{
  int x = Q.s[Q.head];
  if(Q.head == Q.length)
    Q.head = 1;
  else Q.head++;
  return x;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文