【问题标题】:Linked List: Inserting a name and id number to list链接列表:将名称和 ID 号插入列表
【发布时间】:2015-02-08 20:57:07
【问题描述】:

在将姓名和身份证号插入列表时需要帮助。尝试时崩溃 将数字添加到列表中

struct node {

int id;
char name[50];
struct node *next;
} *head;


struct node *insert(struct node * list, char nam[50], int id){

struct node *helper;
struct node *pNew;
pNew=(struct node*)malloc(sizeof(struct node));

strcpy(pNew->name, nam);
pNew->id = id;
pNew->next=NULL;

helper=list;

if (list == NULL)
    return pNew;

while (helper->next!=NULL)
    helper=helper->next;

helper->next=pNew;


return list;

}

int main()
{

char nameInsert[50];
char nameDelete[50];
int idNum, i;
struct node *n=NULL;

//beginning of linked list, must initialize
head = NULL;

//read in data using file input function
readDataFile();

//display data operations using while loop
while(1)
{
    printf("\nData Operations\n");
    printf("\n--------------\n");
    printf("1. Insert Name\n");
    printf("2. Display Names\n");
    printf("3. Delete by ID Number\n");
    printf("4. Delete by Name\n");
    printf("5. Exit\n");
    printf("Please enter a command: ");

    if(scanf("%d", &i) <= 0)
    {
        printf("Not valid input, please use integers 1 - 5");
        exit(0);
    }
    else
    {
        //beginning of switch case
        switch(i)
        {
            case 1:
                printf("Enter the name you would like to insert: ");
                scanf("%s",nameInsert);
                printf("Enter the ID number associated with the name: ");
                scanf("%d", &idNum);
                insert(n,nameInsert, idNum); //insert function
                break;

读取数据文件并将数据存储为链表的应用程序。 提示用户输入学生姓名提示用户输入学生编号用数据填充链表节点的实例将新节点添加到现有链表中

【问题讨论】:

  • 请不要投malloc()和family的返回值。
  • 请告诉我们pNew-&gt;name 是否分配了内存。是name 还是char *
  • 请告诉我们struct node的定义
  • if(scanf("%d", &amp;i) &lt;= 0) 我认为你的逻辑有点错误。 scanf() 返回成功扫描的项目数,而不是输入值。
  • 它带我到正确的案例。它问我名字然后是id然后它崩溃了。它给了我这个错误':(lldb)

标签: c insert linked-list


【解决方案1】:

我已经简化和修改了你的insert()函数

struct node *insert(struct node * list, char *nam, int id){
    struct node *pNew;
    pNew=malloc(sizeof(struct node));
    if (pNew == NULL) {
        printf ("Unable to allocate memory\n")
        exit (1);
    }
    strncpy(pNew->name, nam, 49);       // limit the string copy length
    pNew->name[49] = 0;                 // precautionary terminator
    pNew->id = id;
    pNew->next = list;                  // point to list passed
    return pNew;                        // return new list
}

而你调用insert()的方式忽略了它的返回值,也就是新的列表头/根。

n = insert(n, nameInsert, idNum);   // use the return value

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-09
    相关资源
    最近更新 更多