在c中的链接列表中的某个位置插入节点

时间:2014-05-01 18:27:58

标签: c linked-list

typedef struct list{
      int number;
      struct list *next;
    }LIST;

    void p(struct list *head, int pos, int data){
         struct list *p=head, *q, *p_n=NULL;
         int i=1;

        p_n = (struct list *)malloc(sizeof(struct list));
        p_n->number=data;

        while ((p->next!=NULL) && (i!=pos)) {
            i++;
            p=p->next;
        } 

        if(p->next==NULL){
        p_n->next=NULL;
        p->next = p_n;
        else{
        q=p->next;
        p->next=p_n;
        p_n->next=q;
        }
    }

亲们,我需要帮助。函数p应该将数据插入到特定位置的链表中。 Everithing很好,但是这个函数将数据插入位置+ 1,我不知道为什么。如果你告诉我帮助,我将非常感激。

谢谢:)

2 个答案:

答案 0 :(得分:0)

您可以从 i = 0 开始,而不是1!

答案 1 :(得分:0)

您应该注意几点。

  1. 您应该传递struct list **headp而不是struct list *head,并使用*headp访问该信息。只有这样,您的函数中对head所做的更改才会反映在您的调用函数中。

  2. 插入第一个元素时会发生什么?您的头部为NULL,访问p->next会在Linux中出现分段错误。所以你应该在做任何其他事情之前检查NULL,如果它不是NULL那么只进行下一步。如果是NULL,则应直接将新节点分配给head

  3. typedef struct如果你没有使用它,究竟是什么意思?

  4. 运行代码时会发生这种情况。假设您正在i th 位置插入。您将找到i th 节点,并将在其右侧添加新节点。这将使新节点i + 1 th

    相反,您可以找到i-1 th 节点并将节点插入其右侧。将while循环中的条件更改为p->next!=NULL && i<pos

    祝你好运!