我正在尝试创建一个方法,让我在我喜欢的列表中插入一个新节点在选定的索引,当插入索引0或1时,它目前按预期工作,但当我试图插入任何索引>= 2时,列表中的第一个值正在丢失。知道为什么吗?
主要例子:
#include <stdio.h>
#include <stdlib.h>
#include "list.h"
int main( void ) {
List list = new_list();
add(list, "Three");
add(list, "Two");
add(list, "Zero");
print_list(list);
printf("Inserting at 1 n");
insert_at(list, 1, "one")
print_list(list);
printf("Inserting at 2 n");
insert_at(list, 2, "inserted")
print_list(list);
头文件:
typedef struct Node{
char *value;
struct Node *next;
}Node;
typedef Node** List;
List new_list();
Node *new_node(char *value);
void add(List list,char *value);
int is_empty(List list);
void print_list(const List list);
int insert_at(List list,int index,char *value);
方法文件:
#include <stdlib.h>
#include <stdio.h>
#include "list.h"
#include <string.h>
List new_list(){
List list = malloc(sizeof(List));
*list = NULL;
return list;
}
Node *new_node(char *value){
Node *node = malloc(sizeof(Node));
node->value = value;
node->next = NULL;
return node;
}
void add(List list,char *value){
if (*list == NULL){
*list = new_node(value);
}else {
Node *node = new_node(value);
node->next = *list;
*list = node;
}
}
int is_empty(List list){
if (*list == NULL){
return 1;
} return 0;
}
void print_list(const List list){
printf("[");
Node *curr = *list;
if (curr == NULL){
printf("]n");
return;
}
while (curr->next != NULL){
printf(""%s", ", curr->value );
curr = curr->next;
}
printf(""%s"", curr->value );
printf("]n");
}
int insert_at(List list,int index,char *value){
if ((index > 0 && is_empty(list) == 1) || index < 0){
return 0;
}
int i= 0;
if (index == 0){
add(list, value);
return 1;
}
while((*list) != NULL){
//advancing loop
i++;
//checking if wanted index = lists index
if (i == index){
//creating new node
Node *node = new_node(value);
//updating next values;
node->next = (*list)->next;
(*list)->next = node;
return 1;
}
(*list) =(*list)->next;
}
return 0;
}
示例输出:
["Zero", "Two", "Three"]
Inserting at 1
["Zero", "One", "Two", "Three"]
Inserting at 2
["One", "INSERTED", "Two", "Three"]
在这个while循环中
while((*list) != NULL){
//advancing loop
i++;
//checking if wanted index = lists index
if (i == index){
//creating new node
Node *node = new_node(value);
//updating next values;
node->next = (*list)->next;
(*list)->next = node;
return 1;
}
(*list) =(*list)->next;
}
声明
(*list) =(*list)->next;
覆盖指向头节点的指针,这至少会导致大量内存泄漏。
第二个函数参数应该是无符号整数类型,例如size_t
。
函数new_list
应该至少看起来像
List new_list(){
List list = malloc(sizeof( *list ));
*list = NULL;
return list;
}
一般来说,使用这样的typedef
是一种不好的方法typedef Node** List;
它只会使代码的读者感到困惑。