为什么我的代码在 IDE 中使用与 LeetCode 中相同的测试用例,但在 LeetCode 中这段代码不起作用?

问题描述 投票:0回答:1

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 行:字符 26:运行时错误:在“ListNode”类型的空指针内访问成员 (solution.cpp) 摘要:UndefinedBehaviorSanitizer:undefined-behavior prog_joined.cpp:27:26

我什至不知道我应该尝试什么

c++ linked-list runtime-error singly-linked-list function-definition
1个回答
0
投票

您的函数实现与删除从列表末尾开始的节点没有任何共同之处。

这个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
© www.soinside.com 2019 - 2024. All rights reserved.