Hi guys, I am supposed to implement a sequence using linked list. But I seem to have an error in the code. As I am getting trash for the results of the concatenate function. It might be a problem with my constructor too. I am not sure. Please help. I have pasted the code.
#include <iostream>
using namespace std;
typedef int ElementType;
struct Node
{
ElementType data;
Node* next;
};
class Sequence
{
public:
Sequence();
Sequence(ElementType s);
~Sequence();
Sequence concatenate(Sequence &s);
void insert(ElementType s);
ElementType remove();
bool isEmpty();
void printSeq();
private:
Node* head;
};
#include "sequence.h"
Sequence::Sequence()
{
head = NULL;
}
Sequence::~Sequence()
{
while(head != 0)
{
Node* iter = head;
head = head->next;
delete iter;
}
}
Sequence::Sequence(ElementType s)
{
Node *temp = new Node;
temp->data = s;
temp->next = head;
head = temp;
}
void Sequence::insert(ElementType s)
{
Node *temp = new Node;
temp->data = s;
temp->next = head;
head = temp;
}
ElementType Sequence::remove()
{
ElementType delnode;
Node* temp;
if (head != NULL)
{
temp = head;
head = head->next;
delete temp;
}
return delnode;
}
Sequence Sequence::concatenate(Sequence &seqb)
{
Sequence seqc;
Node* iterator = head;
while (iterator != NULL)
{
seqc.insert(iterator->data);
iterator = iterator->next;
}
Sequence tempseq;
while (seqb.isEmpty() == false)
{
ElementType bnode;
bnode = seqb.remove();
seqc.insert(seqb.remove());
tempseq.insert(bnode);
}
while (tempseq.isEmpty() == false)
{
ElementType tnode;
tnode = tempseq.remove();
seqb.insert(tnode);
}
return seqc;
}
bool Sequence::isEmpty()
{
return(head == NULL);
}
void Sequence::printSeq()
{
Node* iterator = head;
if (head != NULL) {
do
{
cout << iterator->data << " ";
iterator = iterator->next;
}while(iterator != NULL);
}
cout << endl;
}
int main()
{
cout << "Some simple normal tests" << endl;
Sequence s1;
//some inserts
s1.insert(4);
s1.insert(8);
s1.insert(15);
s1.insert(16);
s1.insert(23);
s1.insert(42);
//Should print out list
cout << "List printed is: ";
s1.printSeq();
cout << "It should be 42 23 16 15 8 4" <<endl;
s1.remove();
s1.remove();
s1.remove();
cout << "List printed is: ";
s1.printSeq();
cout << "It should be 15 8 4" <<endl;
Sequence s2 = s1;
cout << "Should be same list again." <<endl;
s1.printSeq();
cout << "Should be same list again." << endl;
s1 = s2;
s1.printSeq();
cout << "This is s2." << endl;
s2.printSeq();
s1.insert(8);
s1.insert(15);
s1.insert(16);
cout << "These two should be different" << endl;
s1.printSeq();
s2.printSeq();
Sequence s3 = s1.concatenate(s2);
cout << "This is the concatenated list" << endl;
s3.printSeq();
cout << "Sequence 1" << endl;
s1.printSeq();
cout << "Sequence 2" << endl;
s2.printSeq();
}