在给定位置插入节点

时间:2018-11-16 05:56:57

标签: c linked-list

节点未插入到该位置。我是编码和处理链表的新手。这里的头指向我已全局声明的开始。请帮助我修改代码

void insert_at_position(struct node **head, int x, int pos)
{
    struct node *temp,*t,*tails = *head;
    t = (struct node*)malloc(sizeof(struct node));
    if (start == NULL)
    {
        start = t;
        start->data = x;
        start->next = NULL;
        return;
    }
    count++;
    while (temp->next!=NULL)
    {
        tails = temp;
        temp = temp->next;
        if (i == pos)
        {
            tails->next=t;
            t->data=x;
            t->next=temp->next;
            return;
        }
        i++;
    }
}

3 个答案:

答案 0 :(得分:0)

  1. count变量的用途是什么,为什么i没有在任何地方声明?请更正。

  2. 在您的while条件内,您需要处理pos == 0情况-

  3. 下面的代码将起作用


int insertNode(int pos, int data)
{
    struct node *temp = NULL, *tails = NULL, *p = NULL;
    p = (struct node*)malloc(sizeof(struct node));
    p->data = data;
    p->next = NULL;
    if(pos == 0)
    {
        p->next = start;
        start = p;
        return 0;
    }
    temp = tails = start;

    while(temp != NULL)
    {
        temp = temp->next;
        pos--;

        if(pos == 0)
        {
            tails->next = p;
            p->next = temp;
            return 0;
        }
        tails = tails->next;
    }

    if(pos)
        printf("\nError!!! Invalid position, can't insert\n");
    return 0;
}

答案 1 :(得分:0)

  1. 代码中的一个问题是make install未初始化,因此temp不会在声明期间指向下一个节点temp->next
  2. 我没有被宣布。
  3. 如果start为NULL,则将新节点插入到pos = 0位置,而不考虑该函数作为参数(temp = *head)给出的位置。
  4. 在您的代码中,当链接列表中的节点数为1(仅头节点)时,不会将新节点添加到pos
  5. 在您的代码中,新节点将仅插入pos=0位置,而不会插入pos+1。在满足pos条件的while循环迭代过程中,tails指向位置2的节点,因此您应该将节点插入tails_pervious节点和tails节点之间,但是将其插入到tails_tails_next之间,这是不正确的。

可以使用以下代码。该代码仅对原始代码进行了少量修改(以便您可以轻松地理解错误)。

i == pos

但是我想提出一些改进:-

  • 最好对函数使用返回类型,以便调用者函数可以检查操作是否成功。
  • 减少函数中的退出点始终是一种好的编程习惯,即尝试减少函数中的return语句。您可以使用少量if-else检查(很值得)来轻松协商return语句的使用

答案 2 :(得分:0)

  • 在需要之前不要分配
  • 利用指针的力量
  • 处理在顶部插入(pos = 0)的情况
  • 处理pos>列表长度的情况

void insert_at_position(struct node **head, int x, int pos)
{
    struct node *new;

    if (!head) { // defensive
          return;
          }

        // Walk the list, until we
        // reach the end
        // or we have passed 'pos' nodes
    for (       ; *head; head = &(*head)->next) {
        if (!pos) break;
        pos --;
        }

     if (pos) { // list too short
        return;
        }

    new = malloc (sizeof *new);
     if (!new) { // malloc failed
        return;
        }
    new->data = x;
    new->next = *head;
    *head = new;
}
相关问题