写一函数建立一个有3名学生数据的单向动态(静态)链表

版权声明:转载请注明出处 https://blog.csdn.net/nanhuaibeian/article/details/88068487

1. 动态表示

#include <stdio.h>
#include <malloc.h>
#define LEN sizeof(Node)
typedef struct Node{
	long num;
	float score;
	struct Node *next;
}*Linklist,Node;
int n;	//全局变量,用来记录有几个学生
// 建立链表的函数
Linklist creat(){
	Linklist head,p1,p2;
	n=0;
	p1=p2=(Linklist)malloc(LEN);
	scanf("%ld,%f",&p1->num,&p2->score);
	head = NULL;
		//尾插法建立链表 
	while(p1->num!=0){
		n++;
		if(n==1)	head = p1;
		else p2->next=p1;
		p2 = p1;
		p1 = (Linklist)malloc(LEN);
		scanf("%ld,%f",&p1->num,&p1->score);
	}
	p2->next = NULL;
	return(head);
}
//输出链表的函数
void print(Linklist head){
	Linklist p;
	printf("\nThese %d records are:\n",n);
	p = head;
	if(head!=NULL)
		while(p!=NULL){
			printf("%ld,%5.1lf\n",p->num,p->score);
			p= p->next;
		} 
}

void main(){
	Linklist head;
	head = creat();
	print(head);
}

2. 静态表示

#include <stdio.h>
typedef struct Node {
	long num;
	float score;
	struct Node *next;
}*Linklist,Node;

// 建立链表的函数
void main(){
	
	Linklist head,p;
	Node a,b,c;
	a.num = 10101;
	a.score = 56;
	b.num = 10102;
	b.score = 78;
	c.num = 10103;
	c.score = 89;
	head = &a;
	a.next = &b;
	b.next = &c;
	c.next = NULL;
	printf("\nThese %d records are:\n",n);
	p = head;
	if(head!=NULL)
		while(p!=NULL) {
			printf("%ld,%5.1lf\n",p->num,p->score);
			p= p->next;
		}

}

猜你喜欢

转载自blog.csdn.net/nanhuaibeian/article/details/88068487