【问题标题】:Linked List nodes disappear while adding (nodes showing garbage values)链表节点在添加时消失(节点显示垃圾值)
【发布时间】:2022-06-16 22:39:26
【问题描述】:

我需要从文本文件中读取一组数据并将它们作为节点添加到链表中。链表需要根据数据中存在的studentID是有序列表。

我做了以下代码。但是当我检查输出时,一些节点似乎丢失并显示垃圾值。可能是什么问题?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct student {
    int studentId;
    struct student *next;
};

typedef struct student Student;
typedef Student *StudentPtr;

void insert(StudentPtr *start, int sId);

int main()
{
    int sId;
    
    FILE *fp;
    
    fp = fopen("w3.txt", "r");
    
    StudentPtr start = NULL;
    fscanf(fp, "%s %d %s %d", sName, &sId, cName, &cId);
    
    
    while(!feof(fp))
    {
        insert(&start, sId);
        fscanf(fp, "%s %d %s %d", sName, &sId, cName, &cId);
        
    }
    
    fclose(fp);
    return 0;
}

void insert(StudentPtr *start, int sId)
{
    StudentPtr prev = NULL, current = NULL;
    StudentPtr newNode = (StudentPtr)malloc(sizeof(StudentPtr));
        
    newNode->studentId = sId;
    newNode->next = NULL;   
    current = *start;
    prev = NULL;
        
    while(current != NULL && current->studentId < newNode->studentId)
    {
        prev = current;
        current = current->next;
            
    }
        
    if(prev == NULL)
    {
        newNode->next = *start;
        *start = newNode;
    }
    else
    {
        prev->next = newNode;
        newNode->next = current;    
    }
            
    //This part is for checking how the node have been added
    current = *start;
    while(current != NULL)
    {
        printf("%d-", current->studentId);
        current = current->next;
    }
    printf("\n");
}

【问题讨论】:

  • sName 是什么?

标签: c structure


猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-01-18
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
  • 2019-07-28
  • 2012-03-15
相关资源
最近更新 更多