问题描述
借助队列,编程实现栈的入栈和出栈操作。
核心步骤
-
厘清队列与栈的特性
-
入栈操作
-
出栈操作
-
编程实现
#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("
溢出");
}
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;
}
}