I'm writing a linked list, and using my main
function to test it. Here's my code:
#include <iostream>
using namespace std;
class LinkedList {
int value;
LinkedList* next;
public:
LinkedList(int valueIn, LinkedList* nextIn) {
value = valueIn;
next = nextIn;
}
LinkedList(int valueIn) {
value = valueIn;
}
int getValue() {
return value;
}
void addNode(LinkedList* node) {
next = node;
}
LinkedList& getNext() {
return *next;
}
};
int main() {
cout << "starting..." << std::endl;
LinkedList list1(1);
LinkedList list2(2, &list1);
cout << list1.getValue() << " --> " << list1.getNext().getValue() << std::endl;
return 0;
}
I expect the output to be 1 --> 2
, but I get 1 -->
. As far as I understand, getNext()
should return a reference to another list (list2
in this case), but something seems to be going wrong. My debugging efforts show me that list2
does have the correct value
2 when it's initialized, but when it's referenced for the final output, it doesn't seem to have anything for value
. I can't for the life of me figure out why this is. Could someone help me to understand?
CodePudding user response:
You are insertin list1(which is actually a node) to the end of list2, not the other way around, yet you call getNext()
on list1
. You should change the code in main to the below:
int main() {
std::cout << "starting..." << std::endl;
LinkedList list1(1);
LinkedList list2(2, &list1);
std::cout << list2.getValue() << " --> " << list2.getNext().getValue() << std::endl;
return 0;
}
Please note that there are a couple of other things which would be better to change:
- Create a list class and a Node class woud make things clearer
- Initializing the pointer to be
NULL
(ornullptr
from C 11) in theLinkedList(int valueIn)
constructor - Return the pointer to the node in
getNext()
rather than copy the node
CodePudding user response:
You are not getting a blank value. Actually your program is crashing when you are trying to call list1.getNext().getValue()
as getNext()
is returning reference to a NULL.
You are doing the opposite of what you want to do.
Your list2
is pointing to list1
and list1
is pointing to NULL
.
You should change your code with this:
LinkedList list2(2);
LinkedList list1(1, &list2);
cout << list1.getValue() << " --> " << list1.getNext().getValue() << std::endl;