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;
}
std::list.insert, you declare a local variableheadwhen there's already a member variablehead. Later, when you sayhead, the compiler can't guess which one you mean (or rather, it guesses wrong).