weixin_52463018 2021-10-18 18:51 采纳率: 100%
浏览 484
已结题

实现队列所有元素逆置

已知q是一个非空顺序队列,s是一个顺序栈,请设计一个算法,实现将队列q中所有元素逆置

  • 写回答

2条回答 默认 最新

  • 关注
    
    #include<iostream>
    #include<malloc.h>
    using namespace std;
    typedef int QElementType;
    typedef struct Node* NodePtr;
    typedef struct SNode* Stack; //栈 
    
    struct Node{       //链队列结点的结构体 
        QElementType data;
        NodePtr next;
    };
    struct QNode{//链队列的头结点 
        struct Node* front;//队头指针,指向第一个元素 
        struct Node* rear;//队尾指针,指向最后一个元素的下一个位置 
    };
    
    struct SNode{
        QElementType data;
        struct SNode *next;
    }; 
    
    void InitQueue(QNode &Q){
        //构造一个空队列
        Q.front=Q.rear= (NodePtr)malloc(sizeof(struct Node));
        if(!Q.front) cout<<"分配空间失败!";
        Q.front->next=NULL; 
    }
    
    void EnQueue(QNode &Q,QElementType e){//Q是头结点指针 
        //插入元素e为Q的新的队尾元素
        NodePtr p=(NodePtr)malloc(sizeof(struct Node));
        if(!p) cout<<"分配空间失败!"; 
        p->data=e; 
        p->next=NULL;
        Q.rear->next=p;
        Q.rear=p;}
        
    QElementType DeQueue(QNode &Q){//出队列 
        QElementType e;
        if(Q.front==Q.rear) return 0;
        NodePtr p=(NodePtr)malloc(sizeof(struct Node));
        p=Q.front->next;
        e=p->data; 
        Q.front->next=p->next;
        if(Q.rear==p) Q.rear=Q.front;
        free(p);
        return e;
    }
    
    //链栈 
    void Push(QElementType e,Stack S){//入栈
        Stack p=(Stack)malloc(sizeof(struct SNode));
        p->data=e;
        p->next=S->next;
        S->next=p;
    }
    QElementType Pop(Stack S){//出栈
        if(S){
            QElementType e;
            Stack p=(Stack)malloc(sizeof(struct SNode));
            p=S->next ;
            e=p->data;
            S->next=p->next;
            free(p);
            return e;
        } 
        
    } 
    int main(){
        int n; 
        cin>>n;
        QElementType e,item1,item2;
        QNode Q;
        InitQueue(Q);
        Stack S;
        S=(Stack)malloc(sizeof(struct SNode));
        S->next=NULL;
    
        for(int i=0;i<n;i++){
            cin>>e;
            EnQueue(Q,e);
        }
        for(int i=0;i<n;i++){
            item1=DeQueue(Q);
            Push(item1,S);
        }
        for(int i=0;i<n;i++){
            item2=Pop(S);
            cout<<item2<<" ";
        }
    }
        
        
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 10月26日
  • 已采纳回答 10月18日
  • 创建了问题 10月18日

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line