在C+&#x2B中交换两个listNode*

发布于 2025-01-30 19:39:55 字数 984 浏览 5 评论 0原文

请帮忙,我在这里完全迷失了。这是Leetcode问题编号。 24,成对交换节点。 我在筛选中遇到了这个错误。

/**
 * Definition for singly-linked list.
 * 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) {}
 * };
 */
class Solution {
    void recurse(ListNode* head){
        if(head!=nullptr and head->next!=nullptr){
            auto previous = head, current = head->next;
            previous->next = current->next;
            current->next = previous->next->next;
            previous->next->next = current;
            
            recurse(current);            
        }
    }
public:
    ListNode* swapPairs(ListNode* head) {
        auto front = new ListNode(0, head);
        recurse(front);
        return front->next;
    }
};

“错误消息”

Please help, I am totally lost here. This is leetcode problem no. 24, swap nodes in pairs.
I am getting this error in screeshot.

/**
 * Definition for singly-linked list.
 * 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) {}
 * };
 */
class Solution {
    void recurse(ListNode* head){
        if(head!=nullptr and head->next!=nullptr){
            auto previous = head, current = head->next;
            previous->next = current->next;
            current->next = previous->next->next;
            previous->next->next = current;
            
            recurse(current);            
        }
    }
public:
    ListNode* swapPairs(ListNode* head) {
        auto front = new ListNode(0, head);
        recurse(front);
        return front->next;
    }
};

error message

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

浪漫之都 2025-02-06 19:39:55

upd :我添加了一些注释来说明OP的正确的解决方案

        if(head!=nullptr and head->next!=nullptr 
           and head->next->next!=nullptr){
            // p->[c]->[x]->y; swap(c, x); y can be null
            auto previous = head, current = head->next;
            // p->c->x->y
            previous->next = current->next;
            // p->x->y; c->x->y
            current->next = previous->next->next;
            // c->y; p->x->y
            previous->next->next = current;
            // p->x->c->y 
            recurse(current);            
        }

原始答案

UPD: I add some comments to illustrate the OP's correct solution:

        if(head!=nullptr and head->next!=nullptr 
           and head->next->next!=nullptr){
            // p->[c]->[x]->y; swap(c, x); y can be null
            auto previous = head, current = head->next;
            // p->c->x->y
            previous->next = current->next;
            // p->x->y; c->x->y
            current->next = previous->next->next;
            // c->y; p->x->y
            previous->next->next = current;
            // p->x->c->y 
            recurse(current);            
        }

original answer ????

        if(head!=nullptr and head->next!=nullptr){
            auto previous = head, current = head->next;
            previous->next = current->next; // previous->next = head->next->next
            current->next = previous->next->next; // current->next = head->next->next->next

            previous->next->next = current;
            
            recurse(current);            
        }

In this if branch you only checked the head and head->next valid.

However you are attempt to invoke head->next->next->next later. Since head->next->next can be nullptr, your program will stop here.

You can find the right solution in the leetcode platform, and here I only reply on why this code doesn't work.

陌上芳菲 2025-02-06 19:39:55

谢谢tieway59,您是对的,我只是自己想出的。如果 block recurse 函数,我缺少heack中的下一个的heack的另外一个验证。
这是我的工作代码:

class Solution {
    void recurse(ListNode* head){
        if(head!=nullptr and head->next!=nullptr 
           and head->next->next!=nullptr){

            auto previous = head, current = head->next;
            previous->next = current->next;
            current->next = previous->next->next;
            previous->next->next = current;
            recurse(current);            
        }
    }
public:
    ListNode* swapPairs(ListNode* head){
        auto front = new ListNode(0, head);
        recurse(front);
        return front->next;
    }
};

Thank you tieway59, you were right I just figured it out by myself. I was missing one more validation of head->next->next in if block of recurse function.
Here's my working code :

class Solution {
    void recurse(ListNode* head){
        if(head!=nullptr and head->next!=nullptr 
           and head->next->next!=nullptr){

            auto previous = head, current = head->next;
            previous->next = current->next;
            current->next = previous->next->next;
            previous->next->next = current;
            recurse(current);            
        }
    }
public:
    ListNode* swapPairs(ListNode* head){
        auto front = new ListNode(0, head);
        recurse(front);
        return front->next;
    }
};
江南烟雨〆相思醉 2025-02-06 19:39:55

要交换列表的两个存在的相邻节点,就无需像您这样做的那样创建一个新节点

auto front = new ListNode(0, head);

相反,您需要的是通过参考将指针传递给节点。

在C ++库中,已经有标准函数std ::交换可以在您的递归功能中使用。

这是一个演示程序。

#include <iostream>
#include <utility>
#include <functional>

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) {}
 };


void clear( ListNode * &head )
{
    while ( head )
    {
        delete std::exchange( head, head->next );
    }
}

void create( ListNode * &head, const int a[], size_t n )
{
    clear( head );

    for ( ListNode **current = &head; n--; current = &( *current )->next )
    {
        *current = new ListNode( *a++ );
    }
}

std::ostream & display( const ListNode * head, std::ostream &os = std::cout )
{
    for ( const ListNode *current = head; current != nullptr; current = current->next )
    {
        os << current->val << " -> ";
    }

    return os << "null";
}

void swap( ListNode * ¤t )
{
    if ( current && current->next )
    {
        ListNode * &next = current->next;
        std::swap( current, next );
        std::swap( current->next, next->next );
        swap( next );
    }
}

int main()
{
    ListNode *head= nullptr;
    const int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    create( head, a, sizeof( a ) / sizeof( *a ) );
    display( head ) << '\n';

    swap( head );
    display( head ) << '\n';

    clear( head );
}

程序输出是

0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> null
1 -> 0 -> 3 -> 2 -> 5 -> 4 -> 7 -> 6 -> 9 -> 8 -> null

To swap two existent adjacent nodes of a list there is no need to create a new node as you are doing

auto front = new ListNode(0, head);

Otherwise there will be a memory leak.

Instead what you need is to pass a pointer to a node by reference.

There is already standard function std::swap in the C++ library that can be used in your recursion function.

Here is a demonstration program.

#include <iostream>
#include <utility>
#include <functional>

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) {}
 };


void clear( ListNode * &head )
{
    while ( head )
    {
        delete std::exchange( head, head->next );
    }
}

void create( ListNode * &head, const int a[], size_t n )
{
    clear( head );

    for ( ListNode **current = &head; n--; current = &( *current )->next )
    {
        *current = new ListNode( *a++ );
    }
}

std::ostream & display( const ListNode * head, std::ostream &os = std::cout )
{
    for ( const ListNode *current = head; current != nullptr; current = current->next )
    {
        os << current->val << " -> ";
    }

    return os << "null";
}

void swap( ListNode * ¤t )
{
    if ( current && current->next )
    {
        ListNode * &next = current->next;
        std::swap( current, next );
        std::swap( current->next, next->next );
        swap( next );
    }
}

int main()
{
    ListNode *head= nullptr;
    const int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    create( head, a, sizeof( a ) / sizeof( *a ) );
    display( head ) << '\n';

    swap( head );
    display( head ) << '\n';

    clear( head );
}

The program output is

0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> null
1 -> 0 -> 3 -> 2 -> 5 -> 4 -> 7 -> 6 -> 9 -> 8 -> null
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文