当前位置:   article > 正文

【基础】队列的插入和删除--C++源代码(g++ 7.2.0)_数据结构队列的插入和删除代码c++

数据结构队列的插入和删除代码c++
#include <iostream>
using namespace std;

struct Node
{
        int data;
        Node* next;
};

struct Deque
{
        Node* first;
        Node* rear;
};

Deque* insert(Deque* pDeque, int data)
{
        Node* pNode = (Node*)malloc(sizeof(Node));
        pNode->data = data;
        Deque* pDeq = pDeque;

        if(NULL == pDeque)
        {
                pDeq = (Deque*)malloc(sizeof(Deque));
                pDeq->first = pNode;
                pDeq->rear = pNode;
                pDeq->rear->next = NULL;
        }
        else
        {
                pDeq->rear->next = pNode;
                pDeq->rear = pNode;
                pDeq->rear->next = NULL;
        }
        return (pDeq);
}

Deque* del(Deque* pDeque)
{
        if(NULL == pDeque)
        {
                return NULL;
        }

        Deque* pDeq = pDeque;
        Node* temp = pDeq->first;
        if(pDeq->first == pDeq->rear)
        {
                free(temp);
                pDeq->first = NULL;
                pDeq->rear = NULL;
        }
        else
        {
                pDeq->first = pDeq->first->next;
                free(temp);
        }
        return (pDeq);
}

void print(Deque* pDeque)
{
        if(NULL == pDeque)
        {
                return ;
        }
        Node* pNode = pDeque->first;
        while(NULL != pNode)
        {
                printf("%d ",pNode->data);
                pNode = pNode->next;
        }
        printf("\n");
}

int main()
{
        Deque* pDeq = NULL;
        pDeq = insert(pDeq,1);
        pDeq = insert(pDeq,2);
        pDeq = insert(pDeq,3);
        pDeq = insert(pDeq,4);
        pDeq = insert(pDeq,5);
        print(pDeq);

        pDeq = del(pDeq);
        pDeq = del(pDeq);
        pDeq = del(pDeq);
        pDeq = del(pDeq);
        pDeq = del(pDeq);
        pDeq = del(pDeq);
        pDeq = del(pDeq);
        print(pDeq);
        return 0;
}
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/706878
推荐阅读
相关标签
  

闽ICP备14008679号