鱼C论坛

 找回密码
 立即注册
查看: 2220|回复: 4

链表插入死循环

[复制链接]
发表于 2019-5-27 00:56:17 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define LEN sizeof(struct student)//student结构体的大小

struct  student *creat();
int n;
void print(struct student *head);
struct  student *insert(struct student *head);
struct student
{
    int num;
    float score;
    struct student *next;
};
int main()
{
    struct student  *stu;
    stu = creat();
    print(stu);
    print(insert(stu));
    return 0;
}

struct  student *creat()
{
    struct student *head;
    struct student *p1, *p2;
    p1 = p2 = (struct student*)malloc(LEN);
    printf("Enter the num:");
    scanf("%d", &p1->num);
    printf("Enter the score:");
    scanf("%f", &p1->score);
    head = NULL;
    n = 0;
    while(p1->num!=0)
    {
        n++;
        if(n==1)
        {
            head = p1;
        }
        else
        {
            p2->next = p1;
        }
        p2 = p1;
        p1 = (struct student*)malloc(LEN);
        printf("Enter the num:");
        scanf("%d", &p1->num);
        printf("Enter the score:");
        scanf("%f", &p1->score);
    }
    p2->next = NULL;
    return head;
}

void print(struct student *head)
{
    struct student *p;
    p = head;
    while(p!=NULL)
    {
        printf("%d\n", p->num);
        printf("%f\n", p->score);
        p = p->next;
    }

}
struct  student *insert(struct student *head)
{
    struct student *p1, *p2, *p3;
    p1 = head;
    printf("Please enter the num to insert:");
    scanf("%d", &p3->num);
    printf("Please enter the score to insert:");
    scanf("%f", &p3->score);
    if(head == NULL)
    {
        head = p3;
        p3->next = NULL;
    }
   while((p3->num > p1->num)&&(p1!=NULL))
   {
       p2 = p1;
       p1 = p1->next;
   }
    if(p3->num<=p1->num)
       {
           if(p1->next ==NULL)
           {
               head = p3;
               p3->next = p1;
           }
           else
           {
               p2->next = p3;
               p3->next = p1;
           }
       }
    else
    {
        p1->next = p3;
        p3->next = NULL;
    }
    return head;


}
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2019-5-27 00:57:21 | 显示全部楼层
大佬们帮我看看, 我的插入都是死循环,麻烦大佬们提示提示小弟,谢谢大哥~
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-5-27 07:41:20 From FishC Mobile | 显示全部楼层
insert() 函数里应该先为指针分配内存然后再使用。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2019-5-27 12:35:52 | 显示全部楼层
jackz007 发表于 2019-5-27 07:41
insert() 函数里应该先为指针分配内存然后再使用。

问题得到解决,谢谢大佬
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-12-28 01:02:33 | 显示全部楼层
insert()函数怎样为指针分配内存
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-10-5 05:25

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表