首页 > 解决方案 > 给定链表中的反向 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;  
}

标签: c++data-structures

解决方案


您的部分代码中的错误是:

  • Node* next;,在此初始值应设置为NULL

    节点*下一个 = NULL;

  • 没有使用的意义

    Node(){ next = NULL; }

在您的代码中,您可以将其删除。

在函数中进行上述更改reverseKNode()以反转链表中的 k 个节点将被正确执行。

在此之后,如果推送节点的功能被正确实现,那么您将获得所需的输出。

希望这可以帮助!!


推荐阅读