I more or less get the basic idea behind single linked list, but having trouble with inserting elements in a doubly linked list.
Basically I am having trouble linking prev and next pointers to the appropriate nodes.
Thanks in advance for help. Here is how my code looks like.
LinkedList.h
template <class T>
class LinkedList{
protected:
LinkedListNode<T>* head;
public:
LinkedList():head(NULL){}
~LinkedList();
void insert(const T& x);
};
//inserting
template <class T>
void LinkedList<T>::insert(const T& x) {
LinkedListNode<T>* head = new LinkedListNode<T>(head->prev, x, head->next);
if(head != NULL){
head->prev = head->next;
head->next = head;
}
}
LinkedListNode.h
class LinkedListNode{
protected:
LinkedListNode<T>* prev;
T value;
LinkedListNode<T>* next;
LinkedListNode(LinkedListNode<T>* p, const T& x, LinkedListNode<T>* n):prev(p), value(x), next(n) {}
~doublyLinkedListNode();
template <class S> friend class doublyLinkedList;
};
I tried modifying the insert function as following, but it gave segmentation fault.
What is wrong with my implementation?
template <class T>
void LinkedList<T>::insert(const T& x) {
LinkedListNode<T>* head;
if(head == NULL){
head->value = x;
head->prev = NULL;
head->next = head;
}
else{ LinkedListNode<T>* newnode;
newnode->value = x;
newnode->prev = head->next;
newnode->next = newnode;
head = newnode;
}
You’re a victim of variable shadowing.
Lets have a look at your original version:
We’re going to dissect the first instruction of your function:
headis a new variable and your originalthis->headis shadowed. But even if you fix this problem, the initialthis->headis stillNULLand thusthis->head->prevwill result in a segmentation fault. You fix the latter in your second version, but only there’s still something wrong:template
The first error (
#1) is, again, variable shadowing.#2is again a segmentation fault, since you didn’t allocate memory for your head.#3are logical errors. The previous node should be the head itself, and the node following a node shouldn’t be the node itself.