在deque中弹出正面和背面

时间:2016-11-20 15:30:21

标签: c++ deque

我正在尝试使用一些函数实现一个双端队列:front(), back(),push_front(),push_back(),pop_front(),pop_back()。如果我在队列中有一个元素并且我尝试弹出它,则在打印函数中出现“读取访问冲突”,但是我检查deque中是否存在第一个元素。

#include<iostream>
#include<cstdlib>
using namespace std;

struct Nod {
    int info;
    Nod* next, *back;
};

void create_queue(Nod*& p, Nod*& u)
{
    Nod *c = new Nod;
    cout << "c->info: "; cin >> c->info;
    if (!p)
    {
        p = c;
        p->back = NULL;
        p->next = NULL;
        u = p;
    }
    else
    {
        u->next = c;
        c->back = u;
        u = c;
        u->next = NULL;
    }
}

void print_queue(Nod* p, Nod* u)
{
    if (p) {
        Nod *c = p;
        while (c) {
            cout << c->info << " ";
            c = c->next;
        }
    }
    else
        cout << "Deque is empty";
}

int front(Nod *p) {
    return p->info;
}

int back(Nod *u) {
    return u->info;
}

void push_front(Nod*& p, Nod*& u) {
    Nod *c = new Nod;
    cout << "Push front c->info "; cin >> c->info;
    c->next = p;
    p->back = c;
    c->back = NULL;
    p = c;
}

void push_back(Nod*& p, Nod*& u) {
    Nod *c = new Nod;
    cout << "Push back c->info "; cin >> c->info;
    c->back = u;
    u->next = c;
    u = c;
    u->next = NULL;
}

void pop_front(Nod*& p, Nod*& u) {
    if (p) {
        Nod *c = p;
        if (p->next != NULL) {
            p->next->back = NULL;
            p = p->next;
        }
        delete c;
    }
    else
    {
        cout << "Can't pop, deque is empty";
    }
}

void pop_back(Nod*& p, Nod*& u) {
    if (u){
        Nod *c = u;
        if (u->back != NULL) {
            u->back->next = NULL;
            u = u->back;
        }
        delete c;
    }
    else
    {
        cout << "Can't pop, deque is empty";
    }
}

int main()
{
    int n, i = 1;
    Nod *p, *u = new Nod;
    p = NULL;
    u = NULL;
    cout << "Nr nod: "; cin >> n;
    while (i <= n){
    create_queue(p, u);
    i++;
    }
    pop_front(p, u); //problems if there is only one element in deque
    print_queue(p, u);
    system("Pause");
}

1 个答案:

答案 0 :(得分:1)

当只有一个节点时,你<div class="container"> <div class="row parent-row"> <div class="col-lg-4 div-wrap"> <div class="a">A</div> <div class="b">B<br>B<br>B<br>B<br>B</div> <div class="c">C</div> <div class="d">DDDDDDDDDDD DDDDDDDDD DDDDDDDDDDDDDDDDD DDDDD DDDDDDDDDDDDDDDDDD DDDDDDDDDDDDD DDDDDDDD DDDDDDDDDDDDDD</div> </div> </div> </div> @media (min-width: 1200px) { .b{ position:absolute; top: 0; right:0; width: 66.66666667%; padding-right: 15px; padding-left: 15px; min-height:1px; } .d{ position:absolute; right:0; width:100%; padding-right: 15px; padding-left: 15px; min-height:1px; } .div-wrap{ position:initial; clear:both; } .parent-row{ position:relative; clear:both; } } 它,但它永远不会设置为delete,因此你仍然访问那里的内存导致运行时错误。在这里,我写了一个经过修改的nullptrpop_front。特别是pop_back现在将尾部前一个元素的pop_back指针设置为next。如果双端队列中只有一个元素(nullptr),我们会执行head == tail,这会将pop_front设置为head,方法是将其分配给下一个元素。

nullptr