我或多或少地了解了单链表背后的基本思想,但是在将元素插入双链表时遇到了麻烦。基本上我无法将 prev 和 next 指针链接到适当的节点。提前感谢您的帮助。这是我的代码的样子。
链表.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;
}
}
链表节点.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;
};
我尝试如下修改插入函数,但它给出了分段错误。我的实施有什么问题?
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;
}