数据结构与算法--用队列实现栈操作

问题描述

借助队列,编程实现栈的入栈和出栈操作。

核心步骤

  • 厘清队列与栈的特性

  • 入栈操作

  • 出栈操作

  • 编程实现

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
using namespace std;

typedef struct student
{
    int data;
    struct student *next;
}node;

typedef struct stackqueue
{
    node *bottom, *top;
}queue;

//入栈
queue *push(queue *HQ, int x)
{
    node *s;
    s = (node *)malloc(sizeof(node));
    s->data = x;
    s->next = NULL;

    if(HQ->top==NULL)
    {
        HQ->bottom = s;
        HQ->top = s;
    }
    else
    {
        HQ->top->next = s;
    }
    return HQ;
}

// 出栈
queue *pop(queue *HQ)
{
    node *p; int x;
    if (HQ->bottom==NULL)
    {
        printf("\n 溢出");
    }
    else
    {
        x = HQ->top->data;
        p = HQ->bottom;
        if(HQ->top==HQ->bottom)
        {
            HQ->top = NULL;
            HQ->bottom = NULL;
        }
        else
        {
            while(p->next != HQ->top)
            {
                p = p->next;
            }
            HQ->top = p;
            hQ->top->next = NULL;
        }
        return HQ;
    }
}

猜你喜欢

转载自www.cnblogs.com/CocoML/p/12726982.html
今日推荐