我正在尝试实现一个队列类(使用节点结构和队列类)。我遇到了分段错误,我的眼睛让我失望了,我似乎找不到它。我的pushBack
行不通,我很确定我的popFront
可能行不通。我只是希望有人能够在正确的方向上给我一个很好的推动!
另外,如果你还没有弄清楚。我显然对C++很陌生。
#include <iostream>
using namespace std;
struct Node {
int data;
Node* link;
};
class Queue {
public:
Queue();
~Queue();
void pushBack(int d);
bool popFront();
bool isEmpty();
void displayQueue();
private:
Node* back;
Node* front;
};
Queue::Queue() {
back = NULL;
front = NULL;
}
Queue::~Queue() {
while (!isEmpty()) {
popFront();
}
}
void Queue::pushBack(int d) {
Node* temp;
if (temp == NULL) {
return;
} else {
temp->link = NULL;
if (back == NULL) {
back = temp;
front = temp;
} else {
front->link = temp;
front = temp;
}
}
}
bool Queue::popFront() {
if (front == NULL) {
return false;
} else {
Node* removeNode;
removeNode = front;
if (back == front) {
back = NULL;
front = NULL;
} else {
Node* previousFront = back;
while (previousFront->link != front) {
previousFront = previousFront->link;
}
front = previousFront;
front->link = NULL;
}
delete removeNode;
return true;
}
}
bool Queue::isEmpty() {
return (back == NULL);
}
void Queue::displayQueue() {
if (isEmpty()) {
cout << "Queue is empty!" << endl;
} else {
Node *current;
current = back;
cout << endl << "-- BACK -- ";
while (current != NULL) {
cout << current->data << " ";
current = current->link;
}
cout << "-- FRONT --" << endl << endl;
}
}
int main(){
Queue q;
q.displayQueue();
q.pushBack(20);
q.pushBack(30);
q.displayQueue();
q.pushBack(40);
q.pushBack(12);
q.displayQueue();
q.popFront();
q.displayQueue();
return 0;
}