【问题标题】:Shift N Linked List Nodes To Front (C)将 N 个链表节点移到前面 (C)
【发布时间】:2018-07-04 22:27:16
【问题描述】:

这是我在 C 语言中遇到的一个问题。 所以,我们有一个有两个参数的函数:

  1. 结构列表** ptrptr
  2. int K

K 表示我们必须从列表的末尾移动到开头的节点数,如下所示:

我知道如何移动一个元素,但我无法使用 tmps 解决 K 个节点。

如果有任何建议,我将不胜感激。 这是一个节点的代码。

void Shift(node **head){
   node *prev;
   node *curr = *head;
   while(curr != NULL && curr->next != NULL) {
      prev = curr;
      curr = curr->next;
   }
   prev->next = NULL;
   curr->next = *head;
   *head = curr;

}

【问题讨论】:

  • 对于K的任何值,您只需要跟踪2个节点->范围的开始和结束节点。
  • 你快完成了。您需要找到列表的第 K 个最后一个节点,而不是查找列表的最后一个节点。
  • 如果你能做到一个,而不是一次尝试所有K,尝试一次做一个K。然后考虑一次尝试所有K

标签: c algorithm sorting linked-list nodes


【解决方案1】:
// Shift the last N nodes of a linked list to the front of
// the list, preserving node order within those N nodes.
//
// Returns -1 if there are not enough nodes, -2 for invalid N,
// 0 otherwise
int shift(list_t **head, int n) {
    list_t *t1, *t2;
    int i;

    if ((head == NULL) || (*head == NULL))
        return -1;

    if (n <= 0)
        return -2;

    // move initial pointer ahead n steps
    t1 = *head;
    for (i = 0; i < n; i++) {
        t1 = t1->next;
        if (t1 == NULL) {
            return -1;
        }
    }

    t2 = *head;

    // t2 and t1 are now N nodes away from each other.
    // When t1 gets to the last node, t2 will point
    // to the node previous to the last N nodes.
    while (t1->next != NULL) {
        t1 = t1->next;
        t2 = t2->next;
    }

    // move the end nodes to the front of the list
    t1->next = *head;
    *head = t2->next;
    t2->next = NULL;

    return 0;
}

【讨论】:

    【解决方案2】:

    您可以在一个“步骤”中移动完整的K 节点链。 假设列表由N 元素组成,nmk 是位置N-K 的节点,e 是列表的最后一个节点。那么代码将是......

    e->next = *head;
    *head = nmk->next;
    nmk->next = NULL;
    

    现在的诀窍是找到节点 nmk,但如果你不介意,我把这个留给你 :-) 并且不要忘记检查诸如空列表之类的极端情况,N==K,....

    【讨论】:

    • 如果 OP 经常用这个列表做这件事,双向链表会更简单
    • @Mark Benningfield:是的;这将使“查找节点nmk”任务变得更加容易:-)
    • 不是要启动线程;我只是想你可能想在你的回答中提到它。对不起,我应该更清楚。
    猜你喜欢
    • 1970-01-01
    • 2018-12-06
    • 2017-07-14
    • 2019-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-25
    • 2021-01-01
    相关资源
    最近更新 更多