鏈表\共用體

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LEN sizeof(struct Student)
//靜態鏈表
struct Student
{
    int num;
    float score;
    struct Student *next;
};

int main1()
{
    struct Student a, b, c, *head, *p;
    a.num = 10101; a.score = 89.5;
    b.num = 10103; b.score = 90;
    c.num = 10105; c.score = 99;
    head = &a;
    a.next = &b;
    b.next = &c;
    c.next = NULL;
    p = head;
    do
    {
        printf("%ld %5.1f\n", p->num, p->score);
        p = p->next;
    } while (p != NULL);


}
//建立單向動態鏈表
//思路:讓p1指向新開闢的結點,p2指向鏈表中最後一個結點,
//把p1所指的結點連接在p2所致的節點後面,用"p2->next=p1"
int n;
struct Student *creat(void)//定義函數,此函數返回一個指向鏈表頭的指針
{
    struct Student *head;
    struct Student *p1, *p2;
    n = 0;
    p1 = p2 = (struct Student *)malloc(LEN);
    scanf("%ld,%f", &p1->num, &p1->score);
    head = NULL;
    while (p1->num!=0)
    {
        n = n + 1;
        if (n == 1)
            head = p1;
        else
            p2->next = p1;
        p2 = p1;
        p1 = (struct Student *)malloc(LEN);//開闢動態存儲區,把起始地址賦給p1
        scanf("%ld,%f", &p1->num, &p1->score);
    }
    p2->next = NULL;
    return head;
}
//輸出鏈表
void print(struct Student * head)
{
    struct Student *p;
    printf("\n Now, these %d records are:\n", n);
    p = head;
    if (head != NULL)
        do
        {
            printf("%ld %5.1f\n", p->num, p->score);
            p = p->next;
        } while (p!=NULL);
}

int main2()
{
    struct Student *pt;
    pt = creat();
    print(pt);

}
//共用體
//共用體各成員的地址都是同一地址
int main3()
{
    union Date
    {
        int i;
        char ch;
        float f;
    }a;

    a.ch = 'a';
    a.f = 1.5;
    a.i = 40;
    printf("%d\n", a.i);
    printf("%c\n", a.ch);
    printf("%f\n", a.f);

}
//運行出錯!!!!!!!!!!!!!!!!!!!!!!why??????????????????????
union Categ
{
    int clas;
    char position[10];
};
struct
{
    int num;
    char name[10];
    char sex;
    char job;
    union Categ category;

}person[2];//定義結構體數組person,有兩個數組

int main()
{

    int i;
    for ( i = 0; i < 2; i++)
    {
        printf("input data of person:\n");
        scanf("%d %s %c %c", &person[i].num, &person[i].name, &person[i].sex, &person[i].job);
        if 
            (person[i].job == 's')
            scanf("%d", &person[i].category.clas);
        else if (person[i].job == 't')
            scanf("%s", &person[i].category.position);
        else
            printf("error input!\n");



    }
    printf("\n");       printf("\n");       printf("\n");
    for ( i = 0; i < 2; i++)
    {
        if (person[i].job == 's')
            printf("-6d%-10s%-4c%-4c%-10d\n", person[i].num, person[i].name, person[i].sex, person[i].job, person[i].category.clas);
        else
            printf("-6d%-10s%-4c%-4c%-10s\n", person[i].num, person[i].name, person[i].sex, person[i].job, person[i].category.position);
    }


    system("pause");
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章