我正在使用 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/