我试图获取列表中的第一个元素并将其删除。
如果我返回节点(ListNode*
),那么我将无法将其删除。如果我在返回之前将其删除,那么将无法返回,因为它已被删除。
我试图将删除功能保留在函数getFirst()
中,而不是创建单独的remove()
函数。通过创建临时指针,我仍然会遇到同样的问题(无法删除它)。我试图实现删除并忽略了要求的get部分。
ListNode* LinkedList::getFirst(){
ListNode *nodePtr; //traverse the list
if(head == nullptr){
std::cout << "List is empty no node to remove"<< std::endl;
return nullptr;
}
else{
nodePtr = head;
head = head->next;
delete nodePtr;
}
return nullptr;
}
如何返回指针并将其删除?
答案 0 :(得分:1)
您遇到的问题是由于尝试在函数中执行了太多操作而引起的。
不要使用getFirst
来执行除#34之外的任何事情;获取第一个节点&#34;。
此外,从链表中删除第一个节点与删除链表的第一个节点不同。
这是我的建议。
// Return the first node of the linked list.
ListNode* LinkedList::getFirst()
{
return head;
}
// Remove the first node from the linked list.
void LinkedList::removeFirst()
{
if(head != nullptr)
{
ListNode *nodePtr = head;
head = head->next;
delete nodePtr;
}
}
// Detach the first node from the linked list and return the detached node.
LinkedNode* LinkedList::detachFirst()
{
if(head == nullptr){
return nullptr;
}
ListNode *nodePtr = head;
head = head->next;
return nodePtr;
}
用法:
LinkedList l;
//
// Fill up the linked list with nodes.
//
ListNode* first = l.getFirst();
if ( first != nullptr )
{
// Use the first node.
}
// Delete the first node from the linked list.
l.removeFirst();
// Detach the first node from the linked list.
ListNode* first = l.detachFirst();
if ( first != nullptr )
{
// Use the first node.
// ...
// Then delete it.
delete first;
}
答案 1 :(得分:0)
删除不应该删除对象,它应该只从列表中删除它。您必须在列表外删除它。
即:
Node * list::get_head()
{
if(!head)
return nullptr;
else
{
Node * ptr = head;
head = head->next;
ptr->next=mullptr;
return ptr;
}
}
然后:
list l;
Node * ptr = l.getFirst();
...
delete ptr
请注意,这是模板大大改进的事情,您可以使节点存储数据,获取数据副本,删除实际节点,最后返回复制的数据。
答案 2 :(得分:0)
如果您只想返回节点的值,可以试试这个:
int LinkedList::getFirst(){
ListNode *nodePtr; //traverse the list
int node_value;
if(head == nullptr){
std::cout << "List is empty no node to remove"<< std::endl;
return nullptr;
}
else{
nodePtr = head;
node_value = nodePtr->value;
head = head->next;
delete nodePtr;
}
return node_value;
}
显然,你必须改变函数的返回值(我假设它是一个整数)。