链表动态加载范例

#include<stdio.h>
#include<stdlib.h>

#define LEN sizeof(struct Student)

int n = 0;

typedef struct Student
{
    int num;
    int score;
    struct Student *next;
}T_Student;

T_Student *create(int num,  int score)
{
	T_Student *p, *q, *head;
	int inum;
	int iscore;

	if(num == 0)
	{
		printf("init input num error!\n");
		return NULL;
	}

	q = (T_Student *)malloc(sizeof(T_Student));

	if(q == NULL)
	{
		printf("malloc error!\n");
		return NULL;
	}

	q->num = num;
	q->score = score;
	q->next = NULL;

	head = q;

	while(1)
	{
		scanf("%d  %d", &inum, &iscore);

		if((iscore == 0) || (inum == 0))
			break;
	
		p = (T_Student *)malloc(sizeof(T_Student));

		if(p == NULL)
		{
			printf("malloc error!\n");
			return NULL;
		}

		p->num = inum;
		p->score = iscore;
		p->next = NULL;

		q->next = p;
		q = q->next;

	}


	return head;
}

void print(struct Student *head)
{
	struct Student *pr = head;

	while(pr != NULL)
	{
		printf("the student num == %d, socre == %d\n", pr->num, pr->score);
		pr = pr->next;
	}
}

int main()
{
	T_Student *pt;

	pt = create(1, 1);

	print(pt);
	
    return 0;
}


最重要的一步是:
	p->num = inum;
	p->score = iscore;
	p->next = NULL;

	q->next = p;
	q = q->next;
释义: 一般要动态加载一个链表,需要定义三个同样类型的指针,比如: prePtr, nextPtr, Head;
nextPtr用于不断申请新节点;
prePtr用于不断的指向最后一个节点;
Head用于指向头结点,用于返回;

q->next = p;
q = q->next;
就是用来不断的指向最后一个节点;

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值