【问题标题】:insert new node at any index within a single linked list在单个链表中的任何索引处插入新节点
【发布时间】:2013-11-12 02:52:45
【问题描述】:

我将如何创建一个允许我在链表中​​的任何索引处插入新节点的函数?这是结构:

struct node {
    int data;
    struct node* next;
};

这里是函数,注意只有一个双指针、索引和数据参数。

void insertN(struct node** headRef, int index, int data);

这是调用 insertN 后的结果:

[ HEAD ] -> [ 0 ] -> [ 15 ] -> [ 10 ] -> [ 5 ] -> [ NULL ]
insertN( &head, 3, -44);
[ HEAD ] -> [ 0 ] -> [ 15 ] -> [ 10 ] -> [ -44 ] -> [ 5 ] -> [ NULL ]
insertN( &head, 4, -55);
[ HEAD ] -> [ 0 ] -> [ 15 ] -> [ 10 ] -> [ -44 ] -> [-55 ] -> [ 5 ] -> [ NULL ]
insertN( &head, 0, -66);
[ HEAD ] -> [ -66 ] -> [ 0 ] -> [ 15 ] -> [ 10 ] -> [ 5 ] -> [ NULL ]

我知道如何向头部添加一个新节点,但在任何时候都不知道。我的想法是

void insertN(struct node** headRef, int index, int data) {
    struct node* new;
    int i;
    for (i = 0; i <= index; i++) {
        if (i == index) {
            /* move what was here to next node and put in new node */
        }
    }

    return;
}

我只是不确定如何去做这一切,因为如果节点中有东西,我也必须移动所有后续节点。

【问题讨论】:

  • 您不会“移动”链表中的节点。您只需相应地插入和调整指针。

标签: c linked-list


【解决方案1】:

如下图所示,需要在两个节点之间插入节点。

其他3种情况是

  • 在列表开头插入
  • 在列表中间插入
  • 在列表末尾插入。

维护一个 count 并循环遍历列表中的所有元素。这个数 将帮助您跟踪索引。

到达节点后,您必须在其中插入新节点

  • 创建新节点
  • 将前一个节点的下一个指针指向新节点。
  • 将新节点的next指针指向当前节点。

提供完整源代码here

【讨论】:

    【解决方案2】:

    当 index == 0 时,您必须处理一种特殊情况,headRef 将需要更新。或者如果 index 大于列表中的元素数。插入将失败。否则请查看下面的示例代码。

    int insertN(struct node** headRef, int index, int data) {
        /* invalid headRef */
        if (!headRef) {
            return 0;
        }
        /* insert node at index */
        int i;
        struct node* new = (struct node *)malloc(sizeof(*node));
        struct node *scan = *headRef;
        new->data = data;
        new->next = 0;
        /* new head of list */
        if (scan == NULL && index == 0) {
             /* new head node */
             new->next = *headRef;
             *headRef = new;
             return 0;
        }
        /* while not at end of list and not at index */
        for (i = 0; scan != NULL && i <= index; i++) {
            if (i == index) {
                /* move what was here to next node and put in new node */
                new->next = scan->next;
                scan->next = new;
            } else {
                /* advance to next entry in list */
                scan = scan->next;
            }
        }
        /* scan == NULL indicates reached end of list before index */
        return (scan != NULL);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-26
      • 2013-04-14
      • 2021-02-25
      • 1970-01-01
      • 2018-08-30
      • 1970-01-01
      • 2017-01-16
      相关资源
      最近更新 更多