ETA: okay take two, I thought I had the problem fixed, turn out no. Okay so I'm a student on work term teaching myself C++ coming from a background in Java, having done that for the past two years in school. I'm having a tough time with some concepts and thought converting my java labs to C++ would help me understand. The lab is a priority queue, meant to take integers via an insert method and store them in ascending order. The remove method should remove the node at the head. My code compiles but breaks on runtime.
Here's the java code, the insert method is wrong actually and I've corrected it in the C+ version:
class QueueA2{
private DNode head,tail;
private int size;
public QueueA2(){
head = tail = null;
size = 0;
}
public void insert(int x){
DNode n = new DNode();
n.setData(x);
if(size == 0)
head = n;
else{
DNode temp = head;
while(temp != null){
if(x > temp.getData()){
tail.setNext(n);
n.setPrev(tail);
tail = n;
}
else {
if(x < temp.getData()){
temp.setPrev(n);
n.setNext(temp);
head = n;
}
/*else if(x > temp.getData() && x < tail.getData()){*/
}
}
}
size++;
}
public void dequeue(){
if(size == 0)
System.out.println("Cannot Dequeue, queue is empty");
else{
if(size == 1){
head = tail = null;
size = 0;
}
else{
head = head.getNext();
size = 0;
}
}
}
public void print(){
DNode temp = head;
while(head != null){
System.out.print(temp.getData()+ " ");
temp = temp.getNext();
}
System.out.println();
}
}
And this is the C++ code
#include <iostream>
#include "Queue.h"
using namespace std;
Queue::Queue()
{
head = tail = 0;
size = 0;
}
void Queue::insert(int x)
{
DNode *n = new DNode();
n->setData(x);
if(size == 0)
{
head = n;
}
else
{
if(x < head->getData())
{
head->setPrev(n);
n->setNext(head);
n = head;
}
else if(x > tail->getData())
{
tail->setNext(n);
n->setPrev(tail);
n = tail;
}
else if(x > temp->getData() && x < tail->getData())
{
DNode *temp = new DNode();
temp = head;
while(temp != 0)
{
if(x > temp->getData())
{
temp = temp->getNext();
}
else
{
DNode *prevTemp = temp->getPrev();
n->setNext(temp);
temp->setPrev(n);
n->setPrev(prevTemp);
prevTemp->setNext(n);
}
}
}
}
size++;
}
void Queue::remove()
{
if(size == 0)
{
cout << "Queue is empty \n";
}
else
{
if(size == 1)
{
head = tail = 0;
size = 0;
}
else
{
head = head->getNext();
}
}
}
void Queue::print()
{
DNode *temp = head;
while(temp != 0)
{
cout << temp->getData();
temp = temp->getNext();
}
cout << "\n";
}