p p asked in 電腦與網際網路程式設計 · 1 decade ago

C語言 linking list

不知道有沒有人可以幫我解釋一下,

下面這段程式碼,

#include<stdio.h>

struct student

{

char name[10];

int age;

struct student *next;

student ()

{

printf(\"Input name:\\n\");

scanf(\"%s\",&name);

printf(\"Input age:\\n\");

scanf(\"%d\",&age);

next=0;

}

void show()

{

printf(\"Your name is %s\\n\",name);

printf(\"Your age is %d\\n\",age);

}

};

struct list

{

struct student *head;

list()

{

head=0;

}

void insert()

{

struct student *s;

s=new student();

s->next =head;

head=s;

}

void show()

{

struct student *t;

t=head;

while(t!=0)

{

t->show();

t=t->next;

}

}

};

void main()

{

struct list l;

l.insert();

l.insert();

l.insert();

l.show();

}

2 Answers

Rating
  • 1 decade ago
    Favorite Answer

    #include<stdio.h>

    struct student //定義student的struct

    {

    char name[10];

    int age;

    struct student *next;

    student () //建構子 用以讓使用者輸入資料

    {

    printf("Input name:\n");

    scanf("%s",&name);

    printf("Input age:\n");

    scanf("%d",&age);

    next=0;

    }

    void show() //顯示結果

    {

    printf("Your name is %s\n",name);

    printf("Your age is %d\n",age);

    }

    };

    struct list //定義另一個 list的 struct

    {

    struct student *head;

    list() //建構子初始化head

    {

    head=0;

    }

    void insert() //加入節點

    {

    struct student *s;

    s=new student(); //會向系統要一個 student的struct

    s->next =head;

    head=s;

    }

    void show()

    {

    struct student *t;

    t=head;

    while(t!=0)

    {

    t->show(); //顯示資料

    t=t->next; //把指標指向下一個節點

    }

    }

    };

    void main()

    {

    struct list l;

    l.insert();

    l.insert();

    l.insert();

    l.show();

    用link list的資料結構去儲存一個名字和年齡對應的資料

    每用一次list.insert() 便會新增一個節點到head指標指向的那個節點的前面

    然後head再回到最前面的節點

    最後的show()會將結果資料印出來

  • 1 decade ago

    好難好難好難好難好難好難好難好難好難好難好難好難好難好難好難好難好難好難好難好難好難好難好難好難好難好難好難好難好難好難好難好難好難好難

Still have questions? Get your answers by asking now.