[英]insert linked list nodes in a loop
我正在使用strtok()解析輸入,將字符串轉換為int,然后在while循環中將這個int值插入到鏈表中。
這就是我想要做的(我沒有明確編寫代碼,但是我打算做如下事情):
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;
}
結構定義也如下:
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);
.........
.........
}
這是我嘗試過的代碼。
# include <stdio.h>
# include <stdlib.h>
struct node
{
int data;
struct node *link;
};
struct node *insert(struct node *p, int n)
{
struct node *temp;
/* if the existing list is empty then insert a new node as the
* starting node */
if(p==NULL)
{
if((p=(struct node *)malloc(sizeof(struct node)))==NULL)
{
perror("Error");
exit(0);
}
p-> data = n;
p-> link = p; /* makes the pointer pointing to itself because it
is a circular list*/
}
else
{
temp = p;
/* traverses the existing list to get the pointer to the last node of
* it */
while (temp-> link != p)
temp = temp-> link;
if((temp-> link = (struct node *)malloc(sizeof(struct node)))==NULL)
{
perror("Error\n");
exit(0);
}
temp = temp-> link;
temp-> data = n;
temp-> link = p;
}
return p;
}
void printlist ( struct node *p )
{
struct node *temp;
temp = p;
printf("The data values in the list are\n");
if(p!= NULL)
{
do
{
printf("%d\t",temp->data);
temp=temp->link;
} while (temp!= p);
printf("\n");
}
else
printf("The list is empty\n");
}
void main()
{
int n;
int x;
struct node *start = NULL ;
char buf[BUFSIZ];
while(fgets(buf,BUFSIZ,stdin)!=NULL){
x=atoi(buf);
start = insert ( start, x );
}
printlist ( start );
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.