There are several errors in your code. The
push
functions are wrong and creates (as
Piebald noted) circular links. The destructor is wrong as well.
Try:
#include <iostream>
using namespace std;
class LinkedList
{
private:
struct Node
{
int data;
Node * next;
};
Node * headA;
Node * headB;
void _push( Node * & head, int data);
void _cleanup( Node * head);
public:
LinkedList():headA(nullptr), headB(nullptr){}
~LinkedList(){ _cleanup(headA); _cleanup(headB);}
bool compare();
void pushA(int data){ _push(headA, data); }
void pushB(int data){ _push(headB, data); }
};
void LinkedList::_push( Node * & head, int data)
{
Node * newNode = new Node();
newNode->data = data;
newNode->next = head;
head = newNode;
}
void LinkedList::_cleanup(Node * head)
{
while (head)
{
Node * tmp = head;
head = head->next;
delete tmp;
}
}
bool LinkedList::compare()
{
Node * na = headA;
Node * nb = headB;
if ( !na || !nb ) return false;
while ( na && nb )
{
if ( na->data != nb->data) return false;
na = na->next;
nb = nb->next;
}
return ( (!na) && (!nb));
}
int main()
{
LinkedList l;
l.pushA(7);
l.pushA(9);
l.pushA(11);
l.pushA(5);
l.pushA(3);
l.pushA(1);
l.pushB(7);
l.pushB(9);
l.pushB(11);
l.pushB(5);
l.pushB(3);
l.pushB(1);
cout << l.compare() << endl;;
}