//
// 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;
}