动态链表实现

发布于 2017-12-03  805 次阅读


动态链表实现

代码

#include 
#include 
#include 
struct student // 链表节点 
{
	int num;
	int score;
	struct student * next;	
};
struct student *head,*p1,*p2;  
int n=0;
struct student * creat() // 动态链表节点建立函数 
{
	head = NULL;  
	p1 = p2 = (struct student *)malloc(sizeof(struct student)); // 用malloc动态分配内存 
	scanf("%d %d",&p1->num,&p1->score); 
	while(p1->num != 0) // 当输入的值为0时不建立节点 
	{
		n++;
		if(n == 1) // 把第一个节点值赋给head 
			head = p1;
		else // 动态增加节点 
			p2->next = p1;
		p2 = p1;
		p1 = (struct student*)malloc(sizeof(struct student));
		scanf("%d %d",&p1->num,&p1->score); 
	} 
	p2->next = NULL; // 节点建立完后最后一个节点的下一个赋为NULL(空) 
	return head;
} 
void print(struct student * head1) // 循环打印链表节点函数 
{
	struct student *p3;
	p3 = head1;
	while(p3 != NULL)
	{
		printf("%d-----%d\n",p3->num,p3->score);
		p3 = p3->next; // 更新节点位置 
	}
}
int main()
{
	struct student *p;
	p = creat();
	print(p);
}