出列链接列表

时间:2012-03-19 21:19:49

标签: c++ deque

这是我程序的输出:

Initial Queue
40 30

40 was popped from back
30

New Queue
12 10 8 30

我遇到了函数push_back的问题,我正在考虑push 12 10 8 after 30,换句话说输出应该是30 8 10 12

任何建议

#include <cstddef> 
class ListNode {
public:
ListNode() {next=NULL;};
int get_data() {return data;};
ListNode * get_next() {return next;};
void set_data(int data) {this->data = data;};
void set_next(ListNode *next) {this->next = next;};
private:
int data;
ListNode *next;
};

#include "dequeue.h"
#include <iostream>

int main()
{
DeQueue q;

q.push_back(30);
q.push_back(40);
cout << "Initial Queue" << endl;
cout << q << endl;


    cout << q.pop_back() << " was popped from back" << endl;
    cout << q << endl;
q.push_back(8);
q.push_back(10);
q.push_back(12);
cout << "New Queue" << endl;
cout << q << endl;

}

 #include "dequeue.h"

DeQueue::~DeQueue()
{
delete [] storage;
}
int DeQueue::pop_back()
{

if(storage == NULL){ //queue is empty!
    return -1; //should throw exception
}
int return_data = storage->get_data();
ListNode *tmp = storage;

storage = storage->get_next();
delete tmp;
return return_data;
}



void DeQueue::push_back(int data)//front
{
ListNode *tmp = new ListNode;
tmp->set_next(storage);
tmp->set_data(data);

storage = tmp;
}


ostream & operator <<(ostream &os, DeQueue &q)
{
ListNode *tmp = q.storage;
while(tmp!=NULL){
    os << tmp->get_data() << " ";
    tmp = tmp->get_next();
}
os << endl;
return os;
 }

#include "list.h"
#include <iostream>
using namespace std;

class DeQueue {
friend ostream & operator <<(ostream &os, DeQueue &q);
public:
DeQueue(){storage=NULL;};
~DeQueue();
int pop_front();
int pop_back(); 
void push_front(int data); 
void push_back(int data);
 private:
ListNode *storage;
 };

1 个答案:

答案 0 :(得分:0)

双端队列最有可能是两个指针:ListNode *front, *back;,否则如果你不知道它在哪里,就不可能在没有遍历整个双端的情况下弹出后面。您还应该保存ListNode中的上一个和下一个元素。

在修复之前,无法正确实施pop_backpush_back