我试图编写一个删除链表中元素的函数。我只是在删除列表的头部时遇到了麻烦。我能够删除任何其他元素就好了。这是我的代码(我只包括处理删除头部的函数部分)。
template <class T>
void SinglyLinkedList<T>::remove(std::size_t i) {
//i is the element to be deleted
SinglyLinkedListNode *p=head;
// checks if the size is 0 or if the node isn't in the list
if( size()==0 && i>=size())
return;
//check if first element
if(i==0){
head=head->next;
//delete p;
}
}
我的问题是释放内存(我在这里注释掉删除)。当我像现在一样评论它时它工作正常(但显然会导致内存泄漏)但是当我取消注释它时我会出现分段错误,我不知道为什么。任何帮助,将不胜感激。
更新:对不起,我忘记了其余的代码:以下是实施:
template <class T>
class SinglyLinkedList {
// Nested class representing the nodes in the list.
class SinglyLinkedListNode {
public:
// The value stored in this node.
T value;
// The next node in the sequence.
SinglyLinkedListNode *next;
SinglyLinkedListNode(T value) :
value(value), next(nullptr) {}
SinglyLinkedListNode(T v, SinglyLinkedListNode *n) :
value(v), next(n) {}
// Return the size (length) of the linked list.
std::size_t size();
};
SinglyLinkedListNode *head;
SinglyLinkedListNode *tail;
public:
// Constructs a new SinglyLinkedList from an initializer_list of type T[].
// This is mostly for convenience, especially when testing.
SinglyLinkedList(std::initializer_list<T> items): head(nullptr), tail(nullptr)
{
if (items.size() == 0) {
return;
}
// initializer_lists were designed to be used iteratively,
// so thats what we do.
auto it = items.begin();
while (it != items.end()) {
this->push_back(*it++);
}
}
T* at(std::size_t i);
void push_back(T value);
void push_front(T value);
std::size_t size();
void remove(std::size_t i);
void insert(std::size_t i, T value);
void append(SinglyLinkedList<T> list);
所以我使用初始化列表创建链接列表,然后尝试删除该元素。但它失败了
SinglyLinkedList<int> lst = {100, 200, 300, 400, 500};
lst.remove(0);
更新2:按此处请求我的推送功能
template <class T>
void SinglyLinkedList<T>::push_back(T value) {
//when empty
if(head==nullptr){
head= new SinglyLinkedListNode(value);
tail=head;
}
//when not empty
else{
tail->next= new SinglyLinkedListNode(value);
tail= tail->next;
}
}