单链表的简单操作之输出

一、链表的输出

链表的输出就是一次输出链表中各个结点的数据或输出某个结点的数据。

输出单链表的程序设计思想如下:

 

  1. 定义一个结点结构体指针变量p 
  2. 让p指向链表的第一个结点即头指针所指向的结点
  3. 使用当型循环,循环的条件是p所指向的结点成员point不是NULL,在循环体中执行的下面的操作:

(1)输出指针变量p所指向结点的数据

 

(2)让指针变量p指向链表的下一个结点

 

(3)继续下一轮的循环

 

实例:建立一个含有4个学生信息的单向链表,输入一些数据,然后输出。

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct student
{
	int number ;
	char name[20] ;
	float score ;
	struct student *point ;
};
void main()
{
	struct student *head ,*end ,*next ,*p  ;
	int i ;
	int snumber ;

	char sname[20] ;
	float sscore ;
	head = (struct student *)malloc(sizeof(struct student)) ;
	if (head == NULL)                                                           
		printf("failure!\n") ;
	else
	{	
		printf("Succeed!\n") ;
		scanf("%d,%f",&snumber,&sscore);
		scanf("%s",&sname);
		head->number = snumber ;
		strcpy(head->name,sname);
		head->score = sscore ;
		head->point = NULL ;   //设置当前节点为尾节点
		end=head ;		// 让end指向尾节点
		for (i=1 ; i<4  ; i++)
		{
			next = (struct student *)malloc(sizeof(struct student)) ;  //开辟新节点
			scanf("%d,%f",&snumber,&sscore);
			scanf("%s",&sname);
			next->number = snumber ;
			strcpy(next->name,sname);
			next->score = sscore ;
			next->point = NULL ;	//置新节点为尾节点
			end->point=next ;			//让原来的尾节点中的指针指向新节点
			end=next;
			   
		}
	}
	p = head ;
	printf("number   name    score\n") ;
	while (p->point != NULL)
	{
		printf("%d   %s   %f\n",p->number,p->name,p->score) ;
		p=p->point ;
	}
	printf("%d   %s   %f\n",p->number,p->name,p->score) ;
	
}	// 让end指向尾节点
		for (i=1 ; i<4  ; i++)
		{
			next = (struct student *)malloc(sizeof(struct student)) ;  //开辟新节点
			scanf("%d,%f",&snumber,&sscore);
			scanf("%s",&sname);
			next->number = snumber ;
			strcpy(next->name,sname);
			next->score = sscore ;
			next->point = NULL ;	//置新节点为尾节点
			end->point=next ;			//让原来的尾节点中的指针指向新节点
			end=next;
			   
		}
	}
	p = head ;
	printf("number   name    score\n") ;
	while (p->point != NULL)
	{
		printf("%d   %s   %f\n",p->number,p->name,p->score) ;
		p=p->point ;
	}
	printf("%d   %s   %f\n",p->number,p->name,p->score) ;
	
}

 

 

运行结果:


 

二、指针分析

 

当程序执行完

  

 end  =  head ; 


之后,end和head的内容完全相同,此时两者的point成员均是NULL,在程序执行到

 

 

end = next ;
之后,head和next中的成员变量point的值均变成了next的地址,以此将链表的头指针与后面结点连接起来。

监视结果:

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值