c++ - 给定链表中的反向 K 节点
问题描述
传递的列表是 1->2->3->4->5 并且节点是 2 然后输出应该是 2 1 4 3 5 但是这段代码显示 1 4 3 5 和 1 2 3 4 5 6 和 3 它显示 3 6 5 4
节点类型
class Node{
public:
int data;
Node* next;
Node(){
next = NULL;
}
};
Node* reverseKNode(Node* head_ref, int k){
Node* current = head_ref;
Node* next;
Node* prev = NULL;
int count = 0;
/*reverse first k nodes of the linked list */
while (current != NULL && count < k)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
count++;
}
/* next is now a pointer to (k+1)th node
Recursively call for the list starting from current.
And make rest of the list as next of first node */
if (next != NULL)
head_ref->next = reverseKNode(next, k);
/* prev is new head of the input list */
return prev;
}
解决方案
您的部分代码中的错误是:
Node* next;
,在此初始值应设置为NULL
。节点*下一个 =
NULL
;没有使用的意义
Node(){ next = NULL; }
在您的代码中,您可以将其删除。
在函数中进行上述更改reverseKNode()
以反转链表中的 k 个节点将被正确执行。
在此之后,如果推送节点的功能被正确实现,那么您将获得所需的输出。
希望这可以帮助!!
推荐阅读
- ios - Mac 能识别 iPhone,Xcode 不能
- html - Twitter 时间线未加载
- firebase - 我可以使用 StreamBuilder 在 Firestore 中收听单个文档吗?
- r - data.table 中的 ifelse 函数不会产生正确的值
- firebase - 我可以根据不在数组中的值进行查询吗?
- c# - 如何使用服务器端代码从 http post header 获取表单数据
- c# - 如何根据.net中的字符拆分将数据表行拆分为多行
- css - Ng bootstrap modal在以角度关闭一个模态弹出窗口后没有弹出
- php - 删除 SQL 表列名中的一个字母会破坏我的 PHP 页面。为什么?
- java - 在数字迷宫中找到最短路径,Java