问题
In main function read the data and sort according to number(ascending order using insertion sort) in a linked list.
typedef struct {
char * name;
int no;
} tele;
In this part the elements of the structure ‘tele’ are to be put in a linked list.
typedef struct _node{
tele data;
struct _node *next;
} node;
Input File (First five lines):
80043 CHEBIYYAM
80131 SHUKLA
80200 GANGARAPU
85400 GAURAV
80001 MUDIT
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define row 100 // total number of lines in txt file
typedef struct
{
char *name;
int no;
} tele;
typedef struct _node
{
tele data;
struct _node *next;
} node;
void main()
{
char line[100];
int i;
FILE *fp;
node *current, *temp, *head;
tele *ptr = NULL;
head=current=NULL;
fp = fopen("test.txt","r");
if (fp == NULL)
{
fprintf(stderr, "Error: unable to open file...\n");
}
while(i!=row)
{
temp = (node *)malloc(sizeof(node));
temp = strtok(line, "\\");
temp->data.no = atoi(ptr);
while (NULL != (ptr = strtok(NULL, "\\")))
{
i++;
if(i == 1)
temp->data.name = ptr;
temp->next = NULL;
}
i=0;
if(head==NULL)
{
current=head=temp;
}
else
{
current = current->next = temp;
}
i++;
}
InsertSort(&head);
print(head);
}
void print(node *head)
{
node *current_node = head;
while ( current_node != NULL)
{
printf("%s %s\n", current_node->data.no, current_node->data.name);
current_node = current_node->next;
}
}
void SortedInsert(node** headRef, node * newNode)
{
if (*headRef == NULL || (*headRef)->data.no >= newNode->data.no)
{
newNode->next = *headRef;
*headRef = newNode;
}
else
{
node* current = *headRef;
while (current->next!=NULL)
{
if(current->next->data.no >=newNode->data.no)
{
break;
}
current = current->next;
}
newNode->next = current->next;
current->next = newNode;
}
}
void InsertSort(node ** headRef)
{
node* result = NULL;
node* current = *headRef;
node* _next = NULL;
while (current!=NULL)
{
_next = current->next;
SortedInsert(&result, current);
current = _next;
}
*headRef = result;
}**
Expected Output:
80001 MUDIT
80043 CHEBIYYAM
80131 SHUKLA
80200 GANGARAPU
85400 GAURAV
How to read number and name separately and store them into a linked list in a node and sort it? I have not written the entire program(so not yet compiled). The main Problem is reading number and name separately and storing it in a linked list.
来源:https://stackoverflow.com/questions/61320647/read-data-from-txt-file-in-c-and-add-it-to-linked-list