c - 在循环中插入链表节点

标签 c linked-list

我正在使用 strtok() 来解析输入,将字符串转换为 int,然后将此 int 值插入到链表中,所有这些都在 while 循环中完成。

这就是我想要做的(我没有明确地编写代码,但我打算做如下的事情):

while(fgets(&string,LMAX,fp) != NULL){

//get first token using strtok
//convert to int
//insert into linked list

while (token != NULL){

//get next token in the line
//do the same as above
}
}

我已经写了一个函数,它应该将一个节点插入到链表中,如下所示:

void insert_node(struct Cons *head_pointer, int data){
struct Cons *new = (struct Cons*) malloc(sizeof(struct Cons));
struct Cons *current = head_pointer;
new->head = data;
new->tail = NULL;

if (head_pointer->tail == NULL){
head_pointer->tail = new;
}
else
{

while (current->tail != NULL){
current = current->tail;
}
current->tail = new;
}
free(current);
current = NULL;
}

struct定义也如下:

typedef int element_t;

typedef
struct Cons {
  element_t head;
  struct Cons* tail;
} Cons;

谁能建议我该怎么做?

最佳答案

这样修改代码

   Cons *insert_node(Cons *head_pointer, int data){
        Cons *new = (struct Cons*) malloc(sizeof(struct Cons));
        Cons *current = head_pointer;
        new->head = data;
        new->tail = NULL;

         if (head_pointer== NULL){
             head_pointer->tail = new;
         }
      else
       {

            while (current->tail != NULL){
               current = current->tail;
       }
           current->tail = new;
    }
 //free(current);
  //current = NULL; 
    return head_poiner;
  }

在 main() 函数调用中;

    main()
     {
      ..........
      ..........
      while(fgets()!=NULL){

       head_pointer=insert_node(head_pointer,data);
     .........
     .........

     }

关于c - 在循环中插入链表节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29313024/

相关文章:

c++ - 确定导致段错误的代码行?

c - C 的注释中的符号 (@) 是什么意思?

c - 皮格马利翁变换 : using "#define DLL" as replacement for "extern "C"__declspec(dllexport)"

c++ - 列表中倒数第二个元素的迭代器

将一行函数转换为c中的宏

c - 警告 : Comparison between pointer and integer and escape characters

java - ArrayList 与 LinkedList 的随机访问和添加删除

Java链表查找和删除方法

c - 从二进制文件读取/写入链接节点

c# - 如何替换 LinkedList 中的元素?