标题:请教一个链表的数据输入的问题
只看楼主
mk_zhou
Rank: 2
来 自:历代兵家必争之地
等 级:论坛游民
威 望:1
帖 子:78
专家分:83
注 册:2015-6-30
结帖率:84.62%
 问题点数:0 回复次数:2 
请教一个链表的数据输入的问题
#include <stdio.h>
#include<stdlib.h>
#define LEN sizeof(struct Student)
struct Student
{
    long num;
    float score;
    struct Student *next;
};
int n;
struct Student *creat()             //输入函数
{
    Student *head;
    Student *p1, *p2;
    n = 0;
    p1 = p2 = (Student*)malloc(LEN);
    /*scanf_s("%ld %f",&p1->num,&p2->score);*/       //为什么使用这种格式输入,程序就会出错呢?
    printf("input the num: ");
    scanf_s("%ld", &p1->num);
    printf("input the score: ");
    scanf_s("%f", &p1->score);
    head = NULL;
    while (p1->num != 0)
    {
        n ++;
        if (n == 1)
        {
            head = p1;
        }
        else
            p2->next = p1;
        p2 = p1;
        p1 = (Student*)malloc(LEN);
        /*scanf_s("%ld %f", &p1->num, &p2->score);*/          //为什么使用这种格式输入,程序就会出错呢?
        printf("input the num: ");
        scanf_s("%ld", &p1->num);
        printf("input the score: ");
        scanf_s("%f", &p1->score);
    }
    p2->next = NULL;
    return (head);
};
void print(Student *head)   //输出函数
{
     Student *p;
    printf("\nNow,These %d record are:\n", n);
    p = head;
    if (head!=NULL)
    {
        do
        {
            printf("%ld %5.1f\n", p->num, p->score);
            p = p->next;

        } while (p!=NULL);
    }
}
struct Student *del(struct Student *head, long num)    //删除指定节点
{
    struct Student *p1, *p2=NULL;
    if (head == NULL)
    {
        printf("\nlist null!\n");
        return(head);
    }
    p1 = head;
    while (num != p1->num&&p1->next != NULL)
    {
        p2 = p1;
        p1 = p1->next;
    }
    if (num == p1->num)
    {
        if (p1 == head)head = p1->next;
        else p2->next = p1->next;
        printf("delete:%ld\n", num);
        n = n - 1;
    }
    else
        printf("%ld not been found!\n", num);
    return head;
}
int main()
{

    Student *head;
    head = creat();
    print(head);
    printf("Please input the num to deleat:");
    scanf_s("%d", &n);
    print(del(head, n));
    return 0;
}

[/code]

发现问题了。。。。
注释掉的输入代码中p1粗心的写成了p2


[此贴子已经被作者于2018-3-19 01:32编辑过]

搜索更多相关主题的帖子: Student num next head printf 
2018-03-19 01:19
mk_zhou
Rank: 2
来 自:历代兵家必争之地
等 级:论坛游民
威 望:1
帖 子:78
专家分:83
注 册:2015-6-30
得分:0 
发现问题了。。代码写错了

仰望星空,看看有没有馅饼落下
2018-03-19 01:27
mk_zhou
Rank: 2
来 自:历代兵家必争之地
等 级:论坛游民
威 望:1
帖 子:78
专家分:83
注 册:2015-6-30
得分:0 
发现问题了。。代码写错了

仰望星空,看看有没有馅饼落下
2018-03-19 01:27



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-485388-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.230577 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved