【发布时间】: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