bosthhe1 / -

数据结构与算法(初阶)
0 stars 0 forks source link

用队列实现栈 #9

Open bosthhe1 opened 1 year ago

bosthhe1 commented 1 year ago

主函数

define _CRT_SECURE_NO_WARNINGS 1

include"head.h"

void MystackPlus(QueueQ obj, QueueQ obj1, int x) { if (!QueueEmpty(obj)) { QueuePlus(obj, x); } else QueuePlus(obj1, x); } void MystackPop(QueueQ obj, QueueQ obj1) { if (!QueueEmpty(obj)) { while (obj->Head->next != NULL) { int y = QueuePop(obj); QueuePlus(obj1, y); } QueuePop(obj); } else { while (obj1->Head->next != NULL) { int y = QueuePop(obj1); QueuePlus(obj, y); } QueuePop(obj1); } }

void TestQueue1() {

Queue* st = myQueueSlist();
MystackPlus(&(st->Q1), &(st->Q2), 1);
MystackPlus(&(st->Q1), &(st->Q2), 2);
MystackPlus(&(st->Q1), &(st->Q2), 3);
MystackPlus(&(st->Q1), &(st->Q2), 4);
MystackPop(&(st->Q1), &(st->Q2));//出栈

} int main() { // 使用2个队列来实现栈 TestQueue1(); return 0; }

bosthhe1 commented 1 year ago

define _CRT_SECURE_NO_WARNINGS 1

include"head.h"

void QueueInit(QueueQ ps) { assert(ps); ps->Head = NULL; ps->Tail = NULL; } void QueuePlus(QueueQ ps,int x) { Queuequeue p = (Queuequeue )malloc(sizeof(Queuequeue)); p->next = NULL; p->x = x; if (p == NULL) { printf("FILE OPEN FAIL"); exit(-1); } if (ps->Head == NULL){ ps->Tail = ps->Head = p; } else { ps->Tail->next = p; ps->Tail = ps->Tail->next; } } int QueuePop(QueueQ ps) { assert(ps); assert(ps->Head); int x = ps->Head->x; Queuequeue newHead = ps->Head->next; free(ps->Head); ps->Head = newHead; if (ps->Head == NULL) ps->Tail = NULL; return x; } bool QueueEmpty(QueueQ ps) { if (ps->Head != NULL) return false; else return true; } void QueueBack(QueueQ ps) { assert(ps); printf("%d ", ps->Tail->x); } void Queuefront(QueueQ ps) { assert(ps); printf("%d ", ps->Head->x); } Queue myQueueSlist() { //创建连个队列,并对队列初始化 Queue Q = (Queue )malloc(sizeof(Queue)); QueueInit(&Q->Q1); QueueInit(&Q->Q2); return Q; }

bosthhe1 commented 1 year ago

pragma once

include

include

include

include

typedef struct Queuequeue { Queuequeue *next; int x; }Queuequeue;

typedef struct Queueq { Queuequeue Head; Queuequeue Tail; }QueueQ; typedef struct Queue//创建两个队列 { QueueQ Q1; QueueQ Q2; }Queue; void QueueInit(QueueQ ps); void QueuePlus(QueueQ ps, int x); int QueuePop(QueueQ ps); void QueueBack(QueueQ ps); void Queuefront(QueueQ ps); bool QueueEmpty(QueueQ ps); Queue* myQueueSlist();