我正在研究一个删除双向链表节点的函数。这是我的头文件:
class LinkedList
{
private:
struct Node
{
int data;
Node *next;
Node *previous;
};
int count;
Node *head;
Node *tail;
public:
LinkedList() {head = NULL; tail = NULL; count = 0;} //Constructor
void insert(const int );
bool remove(const int );
bool contains(const int );
size_t lenght() {return count;}
};
我的其他功能工作正常,但我的删除功能在运行时中断。当我运行我的代码时,我遇到了分段错误,在尝试找出我的逻辑缺陷两天后,我正在向社区寻求帮助。在这一点上,我将不胜感激任何反馈,谢谢。这是我的删除功能:
bool LinkedList::remove(const int item)
{//if the list is empty returns false
if(head == NULL) {return false;}
Node *hptr = head;
Node *tptr = tail;
if((hptr -> data) == item)
{//if the node is at the head of the list
hptr = hptr -> next;
delete head;
hptr -> previous = NULL;
head = hptr;
--count;
return true;
} else if((tptr -> data) == item) {
//if the node is at the tail of the list
tptr = tptr -> previous;
delete tail;
tail = tptr;
tptr -> next = NULL;
--count;
return true;
} else {//if the node is in he middle of the list
Node *ptr_head = head; Node *ptr_headp = NULL;
Node *ptr_tail = tail; Node *ptr_tailp = NULL;
while((ptr_head -> data) != item || (ptr_tail -> data) != item)
{//pointers pass each other then data was not found
if((ptr_tail -> data) < (ptr_head -> data)) {return false;}
//traversing the list from the head and tail simultaniously
ptr_headp = ptr_head;
ptr_head = ptr_head -> next;
ptr_tailp = ptr_tail;
ptr_tail = ptr_tail -> previous;
}
if((ptr_head == ptr_tail) && ((ptr_tail -> data) == (ptr_head -> data)))
{//the item is at the intersection of both head and tail pointers
ptr_headp -> next = ptr_tailp;
ptr_tailp -> previous = ptr_headp;
delete ptr_head;
delete ptr_tail;
--count;
return true;
}
if((ptr_head -> data) == item)
{//the item is before middle node
ptr_headp -> next = ptr_head -> next;
(ptr_head -> next) -> previous = ptr_headp;
delete ptr_head;
--count;
return true;
}
if((ptr_tail -> data) == item)
{//the item is after the middle node
ptr_tailp -> previous = ptr_tail -> previous;
(ptr_tail -> previous) -> next = ptr_tailp;
delete ptr_tail;
--count;
return true;
}
}
return false;
}