在C+&#x2B中交换两个listNode*
请帮忙,我在这里完全迷失了。这是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;
}
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
upd :我添加了一些注释来说明OP的正确的解决方案:
UPD: I add some comments to illustrate the OP's correct solution:
In this
if
branch you only checked thehead
andhead->next
valid.However you are attempt to invoke
head->next->next->next
later. Sincehead->next->next
can benullptr
, 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.
谢谢
tieway59
,您是对的,我只是自己想出的。如果block recurse 函数,我缺少
heack
中的下一个的heack
的另外一个验证。这是我的工作代码:
Thank you
tieway59
, you were right I just figured it out by myself. I was missing one more validation ofhead->next->next
inif block
ofrecurse
function.Here's my working code :
要交换列表的两个存在的相邻节点,就无需像您这样做的那样创建一个新节点
。
相反,您需要的是通过参考将指针传递给节点。
在C ++库中,已经有标准函数
std ::交换
可以在您的递归功能中使用。这是一个演示程序。
程序输出是
To swap two existent adjacent nodes of a list there is no need to create a new node as you are doing
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.
The program output is