0
点赞
收藏
分享

微信扫一扫

动态规划课堂1-----斐波那契数列模型

豆丁趣 03-03 22:01 阅读 2

点击查看题目

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

思路:

在这里插入图片描述

在做此题之前,我们先要实现队列,这在上个博客中已经写过,在这就不在赘述,下面是实现队列的代码
点击进入博客:【数据结构】实现队列

#include<stdio.h>
#include<assert.h>
#include<stdbool.h>


typedef int QDataType;

typedef struct QueueNode
{
	struct Queue* next;
	QDataType val;
}QNode;

typedef struct Queue
{
	QNode* phead;
	QNode* ptail;
	int size;
}Queue;

//初始化
void QueueInit(Queue* pq)
{
	assert(pq);

	pq->phead = NULL;
	pq->ptail = NULL;
	pq->size = 0;
}


//销毁
void QueueDestroy(Queue* pq)
{
	assert(pq);

	while (pq->phead)
	{
		QNode* next = pq->phead->next;
		free(pq->phead);
		pq->phead = next;
	}
	pq->ptail = NULL;
	pq->size = 0;
}


//队尾插入
void QueuePush(Queue* pq, QDataType x)
{
	assert(pq);

	//创建一个新节点
	QNode* newnode = (QNode*)malloc(sizeof(QNode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		return;
	}
	newnode->val = x;
	newnode->next = NULL;

	//插入
	if (pq->phead == NULL)
	{
		pq->ptail = pq->phead = newnode;
	}
	else
	{
		pq->ptail->next = newnode;
		pq->ptail = newnode;
	}
	pq->size++;
}


//队头删除
void QueuePop(Queue* pq)
{
	assert(pq);
	assert(pq->phead);

	Queue* next = pq->phead->next;
	free(pq->phead);
	pq->phead = next;

	if (pq->phead == NULL)
	{
		pq->ptail = NULL;
	}
	pq->size--;
}


//显示第一个节点的值
QDataType QueueFront(Queue* pq)
{
	assert(pq);
	assert(pq->phead);

	return pq->phead->val;
}


//显示最后一个节点的值
QDataType QueueBack(Queue* pq)
{
	assert(pq);
	assert(pq->phead);

	return pq->ptail->val;
}


//是否为空
bool QueueEmpty(Queue* pq)
{
	assert(pq);

	return pq->phead == NULL;
}


//队列的大小
int QueueSize(Queue* pq)
{
	assert(pq);

	return pq->size;
}

现在我们来写本题的代码

typedef struct {
    Queue q1;
    Queue q2;
} MyStack;


MyStack* myStackCreate() {
    MyStack* obj=(MyStack*)malloc(sizeof(MyStack));
    QueueInit(&obj->q1);
    QueueInit(&obj->q2);
    return obj;
}

void myStackPush(MyStack* obj, int x) {
    if(!QueueEmpty(&obj->q1))
    {
        QueuePush(&obj->q1,x);
    }
    else
    {
        QueuePush(&obj->q2,x);
    }
}

int myStackPop(MyStack* obj) {
    Queue* emptyq=&obj->q1;
    Queue* notemptyq=&obj->q2;
    if(!QueueEmpty(&obj->q1))
    {
        emptyq=&obj->q2;
        notemptyq=&obj->q1;
    }

    while(QueueSize(notemptyq)>1)
    {
        QueuePush(emptyq,QueueFront(notemptyq));
        QueuePop(notemptyq);
    }
    int top=QueueFront(notemptyq);
    QueuePop(notemptyq);
    return top;
}

int myStackTop(MyStack* obj) {
    Queue* emptyq=&obj->q1;
    Queue* notemptyq=&obj->q2;
    if(!QueueEmpty(&obj->q1))
    {
        emptyq=&obj->q2;
        notemptyq=&obj->q1;
    }

    return QueueBack(notemptyq);
}

bool myStackEmpty(MyStack* obj) {
    return QueueEmpty(&obj->q1)&&QueueEmpty(&obj->q2);
}

void myStackFree(MyStack* obj) {
    QueueDestroy(&obj->q1);
    QueueDestroy(&obj->q2);
    free(obj);
}

好了,那么本篇博客就到此结束了,如果你觉得本篇博客对你有些帮助,可以给个大大的赞👍吗,感谢看到这里,我们下篇博客见❤️

举报

相关推荐

0 条评论