LeetCode上的问题:https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode **buf = &head;
for (int i = 0; i < n; ++i) {
buf = &(*buf)->next;
}
(*buf) = (*buf)->next;
return head;
}
int main() {
removeNthFromEnd(new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5))))), 2);
return 0;
}
运行时错误第18行:Char 26:运行时错误:在'ListNode'类型的空指针内访问成员(solution.cpp)UndefinedBehaviorSanitizer: undefinedbehavior prog_joined.cpp:27:26
我甚至不知道我应该尝试什么
您的函数实现与从列表末尾开始删除节点没有任何共同之处。
for循环
for (int i = 0; i < n; ++i) {
buf = &(*buf)->next;
}
从列表开始的节点计数。
也可以调用未定义的行为,当列表包含少于n
元素,由于使用空指针访问内存。
您需要使用操作符delete
删除目标节点。
函数可以如下面的演示程序所示。
#include <iostream>
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
bool removeNthFromEnd( ListNode* &head, size_t n)
{
bool success = n != 0;
if ( success )
{
ListNode *last = head;
while ( last && n )
{
last = last->next;
--n;
}
if ( ( success = n == 0 ) )
{
ListNode **current = &head;
while ( last )
{
last = last->next;
current = &( *current )->next;
}
ListNode *tmp = *current;
*current = ( *current )->next;
delete tmp;
}
}
return success;
}
std::ostream & display( const ListNode *head, std::ostream &os = std::cout )
{
for ( ; head != nullptr; head = head->next )
{
os << head->val << " -> ";
}
return os << "null";
}
int main()
{
ListNode *head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))));
display( head ) << 'n';
removeNthFromEnd( head, 2);
display( head ) << 'n';
removeNthFromEnd( head, 4);
display( head ) << 'n';
removeNthFromEnd( head, 2);
display( head ) << 'n';
removeNthFromEnd( head, 1);
display( head ) << 'n';
removeNthFromEnd( head, 1);
display( head ) << 'n';
return 0;
}
程序输出为
1 -> 2 -> 3 -> 4 -> 5 -> null
1 -> 2 -> 3 -> 5 -> null
2 -> 3 -> 5 -> null
2 -> 5 -> null
2 -> null
null