链表的运用

#include<stdio.h>
#include<malloc.h>
#define LEN sizeof(struct student)

typedef struct student

{
        long num;
	float score;
	struct student *next;/*指向链表的下一个结点**/

}stu;					/*声明结构体类型struct student,并取别名为stu*/


int n;
stu *creat(void)		/*创建动态链表函敪*/
{

	stu *head,*p1,*p2;	/*定义结构体类型的指针*/
	n=0;
	p1=p2=(stu *)malloc(LEN);/*开辟一个内存空间*/
	scanf("%ld,%f",&p1->num,&p1->score);/*输入结构体类型的数据*/
	head=NULL;				/*头指针置空**/
	while(p1->num!=0)		/*判断学号输入是否为0,若是0则跳出循环**/
	{
		n=n+1;			
		if(n==1)head=p1;    /*判断是否是输入的第1个数据信息,若是第一个数据信息,则将头指针指向p1*/

		else
			p2->next=p1;	/*将p2指向的下一个地址指向p1*/
		p2=p1;				/*p2指向p1*/
		p1=(stu *)malloc(LEN);/*再次为p1开辟一个内存空间,存储下一个数捪*/
	        scanf("%d,%d,%f",&p1->num,&p1->age,&p1->score);
	}
	p2->next=NULL;			/*p2指向下一个地址指向的是空指钪*/
	return(head);			/*返回数据信息的头指针,以便从头输出**/
}

void print(struct Student head) //输出链表
{
    struct Student *p;
    printf("\nNow These %d records are:\n",n);
    p = head;
    if(head != NULL)
    do
    {
        printf("%ld %5.1f\n",p->num,p->score);
        p = p->next;
    }while(p != NULL);
}

void main()
{
    struct Student *head;
    head = creat();
    print(head);
}

main()

{
	stu *p,*head;
	head = creat();
	p = head;
	if(head!=NULL)
		do
		{
			printf("%d,%d,%f\n",p->num,p->age,p->score);
			p = p->next;
		}while(p!=NULL);
}

	

 

第二题:

Example Input

10
11 3 5 27 9 12 43 16 84 22 

Example Output

22 84 16 43 12 9 27 5 3 11 
//用 (顺序)或逆序建立链表
//输入N个整数,按照输入的顺序建立单链表存储,并遍历所建立的单链表,输出这些数据。
//
#include<stdio.h>
#include<malloc.h>

struct node{

	int data;
	struct node *next;
};

struct node *creat(int n){
	struct node *head,*tail,*p;
	head = (struct node*)malloc(sizeof(struct node));
	head->next = NULL;
	tail = head;
	int i;
	for( i=0; i<n ;i++){
		p = (struct node*)malloc(sizeof(struct node));
		scanf("%d",&p->data);
	//顺序	p->next = p; 	//p1->next=data
	//	tail->next = p;  //如:p2->next = p1
	//	tail = p;//p2 = p1
	
	

	//逆序
		p->next = head->next;
		head->next = p;
	
	}

	// 	tail->next = NULL;//p2->next = NULL	

	return head;
};

void show(struct node *head){
	struct node *p;
	p = head->next;	
	
	if(head != NULL)
	do 
	{
		printf("%d ",p->data);
		p = p->next;//p指向下一个节点

	}while(p != NULL);

	printf("\n");	
}

int main()
{
	int n;
	struct node *head;
	scanf("%d",&n);
	head = creat(n);
	show(head);
	
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值