栈与队列(数据结构)

1.顺序栈

#include <iostream>

using namespace std;
#define MaxSize 50
typedef int ElemType;

typedef struct
{
    ElemType data[MaxSize];
    int top;
}SqStack;
void InitStack(SqStack &S)//要改变栈内的元素或者,top指针
{
    S.top=-1;
}
bool Empty(SqStack S)
{
    if(S.top==-1)return 1;
    else return 0;
}
void push(SqStack &S,ElemType e)
{
    S.top++;
    S.data[S.top]=e;
}
void pop(SqStack &S)
{
    S.top--;
}
int get(SqStack S)
{
    return S.data[S.top];
}

int main()
{
    SqStack s;
    InitStack(s);
    int x;
    do
    {
        cin>>x;
        push(s,x);
    }while(x!=0);
    pop(s);
    while(!Empty(s))
    {
        cout<<get(s)<<" ";
        pop(s);
    }
    return 0;
}

2.链式栈的基本操作

#include <bits/stdc++.h>

using namespace std;
#define MaxSize 50
typedef int ElemType;

typedef struct node
{
    ElemType data;
    struct node *next;
}LStackNode,*LinkStack;
void InitStack(LinkStack *top)//要改变栈内的元素或者,top指针
{
    *top = (LinkStack)malloc(sizeof(LStackNode));
    (*top)->next = NULL;
}
int Empty(LinkStack top)
{
    if(top->next==NULL)return 1;
    else return 0;
}
void pop(LinkStack top)
{
    LStackNode *p=top->next;
    top->next=p->next;//因为是带有头节点的,所以不是top=top->next
    free(p);
}
void push(LinkStack top,ElemType e)
{
    LStackNode *p;
    p = (LinkStack)malloc(sizeof(LStackNode));
    p->data=e;
    p->next = top->next;//注意这两行
    top->next = p;//注意这两行
}
int get(LinkStack top)
{
    return top->next->data;
}
int main()
{
    LinkStack s;
    InitStack(&s);
    while(1)
    {
        int x;
        cin>>x;
        if(x==0)break;
        push(s,x);
    }
    while(!Empty(s))
    {
        cout<<get(s)<<" ";
        pop(s);
    }
    return 0;
}

3.顺序队列

#include <bits/stdc++.h>

using namespace std;
#define MAXSIZE 50
typedef struct
{
    int *base;
    int front;
    int rear;
}Squeue;
void InitQueue(Squeue &s)
{
    s.base = (int *)malloc(sizeof(int));
    s.front = 0;
    s.rear = 0;
}
void push(Squeue &s,int e)
{
    if(((s.rear+1)%MAXSIZE)==s.front)
    {
        exit(-1);
    }
    s.base[s.rear]=e;
    s.rear = (s.rear+1)%MAXSIZE;
}
int out(Squeue &s)
{
    int e = s.base[s.front];
    s.front = (s.front +1)%MAXSIZE;
    return e;
}
int Empty(Squeue s)
{
    if(s.front==s.rear)return 1;
    else return 0;
}
int main()
{
    Squeue s;
    InitQueue(s);
    while(1)
    {
        int x;
        cin>>x;
        if(x==0)break;
        push(s,x);
    }
    while(!Empty(s))
    {
        cout<<out(s)<<" ";
    }

    return 0;
}

©️2020 CSDN 皮肤主题: 游动-白 设计师:上身试试 返回首页