Nov 23, 2015 at 10:40am UTC
I am trying to create a linked list, however when I run the main program the output is unexpected.
Header file:
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
using namespace std;
struct Node
{
int val;
Node *next;
};
class LinkedList
{
public:
LinkedList(); // Constructor
~LinkedList(); // Destructor
void insertAtBack(int valueToInsert);
bool removeFromBack();
void print();
bool isEmpty();
int size();
void clear();
void insertAtFront(int valueToInsert);
bool removeFromFront();
// Private Functions/Variables
private:
Node *first;
Node *last;
};
#endif
LinkedList:
#include <iostream>
#include "LinkedList.h"
using namespace std;
LinkedList::LinkedList() {
Node *first = new Node();
first = NULL;
Node *last = first;
}
LinkedList::~LinkedList() {
while(!isEmpty())
removeFromBack();
}
void LinkedList::insertAtBack(int value) {
Node* node = new Node();
node->val = value;
if (last == NULL) {
last = node;
first->next = last;
}
if (first == NULL) {
first = node;
}
else {
last->next = node;
last = node;
}
}
bool LinkedList::removeFromBack() {
Node* old = last;
last = old->next;
delete old;
}
void LinkedList::print() {
Node* temp = last;
while (temp->next != NULL) {
cout << temp->val << ",";
temp = temp->next;
}
cout << first->val;
}
bool LinkedList::isEmpty() {
return last == NULL;
}
int LinkedList::size() {
Node* temp = last;
int count = 0;
while (temp != NULL) {
count++;
temp = temp->next;
}
return count;
}
void LinkedList::clear() {
while(!isEmpty())
removeFromBack();
}
Program:
#include <iostream>
#include "LinkedList.h"
using namespace std;
int main()
{
LinkedList firstList;
LinkedList secondList;
if(firstList.isEmpty())
cout << "The first list is empty!" << endl;
else
cout << "The first list is NOT empty..." << endl;
if(seoondList.isEmpty())
cout << "The second list is empty!" << endl;
else
cout << "The second list is NOT empty..." << endl;
return 1;
}
The output is the first list is empty but the second one is not empty even though I have not added anything to either list.