C -链表在插入时删除值

t2a7ltrp  于 2022-12-02  发布在  其他
关注(0)|答案(1)|浏览(104)

我试图创建一个方法,让我插入一个新的节点在我喜欢的列表中的一个选定的索引,它目前的工作预期时,插入到索引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"]
deyfvvtc

deyfvvtc1#

在这个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;

它只会让代码的读者感到困惑。

相关问题