【问题标题】:Reverse alternate K nodes in a Singly Linked List反向单链表中的备用 K 个节点
【发布时间】:2016-07-09 23:59:44
【问题描述】:

我从http://www.geeksforgeeks.org/reverse-alternate-k-nodes-in-a-singly-linked-list/得到了这个问题和Java解决方案

给定一个链表,编写一个函数来反转每个交替的 k 个节点 输入:1->2->3->4->5->6->7->8->9->NULL 和 k = 3 输出:3->2->1->4->5->6->9->8->7->NULL。

在他们的 java 代码中:我真的不明白为什么需要第 2 步)。 除了 kAltReverse(Node node, int k) 中的第一个参数之外,节点没有在其他任何地方使用 方法中的这个节点参数在每次递归中都被分配给一个新的变量 current。然后在每个递归中使用 current、prev、next 变量。

那么为什么需要node.next = current in step2)?

 Node kAltReverse(Node node, int k) {
    Node current = node;
    Node next = null, prev = null;
    int count = 0;

    /*1) reverse first k nodes of the linked list */
    while (current != null && count < k) {
        next = current.next;
        current.next = prev;
        prev = current;
        current = next;
        count++;
    }

    /* 2) Now head points to the kth node.  So change next 
     of head to (k+1)th node*/
    if (node != null) {
        node.next = current;   **// why node.next should be moved to current even though node is not impacting on anywhere else in 3), 4)???**
    }

    /* 3) We do not want to reverse next k nodes. So move the current 
     pointer to skip next k nodes */
    count = 0;
    while (count < k - 1 && current != null) {
        current = current.next;
        count++;
    }

    /* 4) Recursively call for the list starting from current->next.
     And make rest of the list as next of first node */
    if (current != null) {
        current.next = kAltReverse(current.next, k);
    }

    /* 5) prev is new head of the input list */
    return prev;
}

【问题讨论】:

    标签: recursion linked-list


    【解决方案1】:

    您的问题与递归没有任何关系,在这种方法中,可以通过简单地保留第一个 prev 而将大部分代码包装在一个 while 循环中来避免递归。这个问题都是关于参考的。

    该过程重新排列链条。就在有问题的代码之前,您有两个未连接的链表:

    3->2->1->null 4->5->...
    \prev \node   \current
    

    设置node.next 时,您正在更改节点引用的对象的属性。因此,您正在替换引用以指向不同的对象。当node.next 用作值时,您将获得对对象的引用。完成node.next = current 后,您将拥有:

    3->2->1->4->5->...
    \prev \  \current
           \node
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-31
      • 1970-01-01
      • 2020-12-25
      • 2018-07-28
      • 2023-03-08
      • 2012-06-20
      • 1970-01-01
      相关资源
      最近更新 更多