今天,我希望使用指针在c ++中创建自己的去队列。在这个程序中,我想要创建两个排程,在其中添加不同的元素。不幸的是,事实并非如此。屏幕上只有6 5,只有6。为什么?我不知道怎么排成两队?我想我的问题之一是*L = NULL, * R = NULL,但我不确定?所以到目前为止我的密码-
#include <iostream>
struct elem
{
int key;
elem* next;
}*L = NULL, * R = NULL;
void push_l(int n, elem*& p)
{
p = L;
L = new elem;
L->key = n;
L->next = p;
if (R == NULL)
R = L;
}
int pop_l(int& n, elem*& p)
{
if (L)
{
p = L;
n = L->key;
L = L->next;
if (L == NULL)
R = NULL;
delete p;
return 1;
}
else
{
return 0;
}
}
int main()
{
int k;
elem* p = new elem;
elem* q = new elem;
push_l(5, p);
push_l(6, q);
while (pop_l(k, q))
{
std::cout << k<< " ";
}
}我不确定如何在屏幕上只打印6,因为这个元素只被推送到排队列中?此外,这些只是脱队列的一些特性,因为我想从一开始就了解它!
发布于 2022-05-13 14:50:20
这样的类可能如下所示:
class /* or struct, if you really want to... */ Dequeue
{
public:
void push(int value);
bool pop(int& value); // if you return 1 for success and 0 for error
// bool is the more appropriate type...
private:
struct elem // it's an implementation detail, so recommendable
// to have it as a nested class...
{
// just as you had before...
// you might additionally provide a constructor:
// this makes creating new instances easier/simpler
elem(int k, elem* n) : key(k), next(n) { }
};
elem* m_head = nullptr;
elem* m_tail = nullptr;
}
void Dequeue::push(int value)
{
// auto tmp = new elem;
// tmp->key = value;
// tmp->next = m_head;
// m_head = tmp;
// with constructor:
m_head = new elem(value, m_head);
if(!m_tail)
m_tail = m_head;
}
bool Dequeue::pop(int& value)
{
// transform analogously using m_head and m_tail instead of L and R
// return true and false instead of 1 and 0
}您会注意到,该函数看起来和以前一样-不过,与现在的成员函数一样,它访问调用该函数的实例的类成员:
Dequeue d1;
Dequeue d2;
// each of these have their own, separate m_head and m_tail pointers!
d1.push(12);
d2.push(10);
// now pushed to separate instances 附带注意:未经测试的代码,如果你发现了一个错误,请自己修复.
https://stackoverflow.com/questions/72231235
复制相似问题