【问题标题】:Inserting elements in list, between every two在列表中插入元素,每两个之间
【发布时间】:2021-04-19 10:50:01
【问题描述】:

我需要编写一个函数,在每两个现有节点之间的单链表中插入一个新节点,其值等于这两个节点的值之差。

例如,如果我们有列表 1→2→5→7,结果应该是 1→1→2→3→5→2→7,因为 2-1=1、5-2=3 和 7-5 =2。

这是我的尝试:

struct Node{
    int v;
    struct Node* next;
};
void insert(struct Node** headPtr){
    struct Node* curr = *headPtr;
    struct Node* new = malloc(sizeof(struct Node));
    while(curr->next!=NULL){
        new->v=curr->next->v-curr->v;
        new->next=curr->next;
        curr->next=new;
        curr=curr->next;
    }
}
void addRear(struct Node** headPtr, int v_new){
    struct Node* new = malloc(sizeof(struct Node));
    new->v=v_new;
    new->next=NULL;
    if(*headPtr==NULL){
        *headPtr=new;
    }else{
        struct Node* curr = *headPtr;
        while(curr->next!=NULL){
            curr=curr->next;
        }
        curr->next=new;
    }
}
void print(struct Node* head){
    struct Node* curr = head;
    while(curr!=NULL){
        printf("%d ",curr->v);
        curr = curr->next;
    }
}

但是当我在main 中运行以下命令时,我没有得到任何结果。这是我的main 代码:

struct Node* head=NULL;
addRear(&head,1);
addRear(&head,2);
addRear(&head,5);
addRear(&head,7);
print(head);
printf("\n");
insert(&head);
print(head);

【问题讨论】:

    标签: linked-list singly-linked-list


    【解决方案1】:

    两个问题:

    • 您只是在创建 一个 新节点。将新节点的创建移动到循环内。
    • curr=curr->next 不正确,因为这样curr 将等于new 节点。因此,在下一次迭代中,您将不会更接近列表的末尾。循环永远不会结束。相反,您应该使用curr = new->next

    以下是更正后的代码:

    void insert(struct Node** headPtr){
        struct Node* curr = *headPtr;
        while (curr->next != NULL) {
            struct Node* new = malloc(sizeof(struct Node)); // <---
            new->v = curr->next->v - curr->v;
            new->next = curr->next;
            curr->next = new;
            curr = new->next; // <---
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-12-08
      • 1970-01-01
      • 2017-01-15
      • 1970-01-01
      • 2015-09-11
      • 2021-06-27
      • 2019-12-28
      • 2012-09-21
      • 2015-12-20
      相关资源
      最近更新 更多