创建链表和显示链表

来源:互联网 发布:我要开手机淘宝网店 编辑:程序博客网 时间:2024/04/29 22:18
 

#include <stdio.h>
#include <stdlib.h>

struct Stud
{
    int no;
    int score;
    struct Stud *next;
};
//创建链表
struct Stud *create()
{
    struct Stud *head, *p, *q;
    int n, s;
    head = (struct Stud *)malloc(sizeof(struct Stud));
    head->next = NULL;
    p = head;
    while(1)
    {
        printf("学号 分数:");
        scanf("%d%d",&n, &s);
        if(n == 0 && s == 0)
        {
            break;
        }
        else
        {
            q = (struct Stud *)malloc(sizeof(struct Stud));
            q->no = n;
            q->score = s;
            q->next = NULL;
            p->next = q;
            p = q;
        }
    }
    return head;
}

//显示链表
void disp(struct Stud *h)
{
    struct Stud *p = h->next;
    printf("输出链表:");

    if(p == NULL)
    {
        printf("空表\n");
    }
    else
    {
        while(p->next != NULL)
        {
            printf("%d %d,", p->no, p->score);
            p = p->next;
        }
        printf("%d %d\n", p->no, p->score);
    }
}

int main()
{
    struct Stud *head;
    head = (struct Stud *)malloc(sizeof(struct Stud));
    head = create();
    disp(head);
    return 0;
}

原创粉丝点击