//

//  main.c

//  dynamic_link_list

//

//  Created by ma c on 15/8/5.

//  Copyright (c) 2015. All rights reserved.

//  要求:寫一個函式建立有3名學生資料的動態單向連結串列,並輸出連結串列中每個結點的所有內容。

/*

建立動態連結串列的思想:

1、開闢一個新結點,並使p1,p2指向它;

2、讀入一個學生資料給p1所指的結點;

3、head = NULL,n = 0;

4、判斷讀入的p1->num是否為0。

如果p1->num!=0,n = n+1;此時n==1?

如果n==1,head=p1(p1所指的結點作為第一個結點)

如果n!=1,p2->next=p1(把p1所指的結點連線到表尾)

p2=p1;(p2移到表尾)

再開闢一個新結點,使p1指向它;

讀入一個學生資料給p1所指接點;

表尾結點的指標變數置NULL。

如果p1->num==0,連結串列結束,退出程式。

輸出連結串列的思想:

1、p=head,使p指向第一個結點

2、判斷p指向的是不是尾節點?

如果不是,輸出p所指向的結點,p指向下一個結點;

如果是,連結串列結束,退出程式。

*/

#include <stdio.h>

#include<stdlib.h>

#define LEN sizeof(Student)

typedef struct student

{

int num;

float socre;

struct student *next;

}Student;

int n;     //定義一個全域性變數

Student *createlist(void)

{

Student *p1,*p2,*head;

int n = 0;

//開闢一個新單元

p1 = p2 = (Student*)malloc(LEN);

//輸入第一個學生的學號和成績

scanf("%d,%f",&p1->num,&p1->socre);

head = NULL;

while(p1->num!=0)

{

n = n+1;

if(n==1)

{

head = p1;

}

else

{

p2->next = p1;

}

p2 = p1;

p1 = (Student *)malloc(LEN);

scanf("%d,%f",&p1->num,&p1->socre);

}

p2->next = NULL;

return head;

}

void printlink(Student *pt)

{

while(pt!=NULL)

{

printf("\nnum:%d\nscore:%5.1f\n",pt->num,pt->socre);//輸出每個結點的成員值

pt = pt->next;

}

}

int main(int argc, const char * argv[])

{

Student *pt;

pt = createlist();//函式返回連結串列的第一個結點的地址

printlink(pt);

return 0;

}