【C系列7.3】结构-3 补充信息

Description

loy最近被分配给了一个任务:将队里的队员信息表补充完整,然而她实在是太懒了,就把这项任务推给了你,你能帮助她吗? 

Input

多组输入

第一行给出两个正整数n,t(0<n,t<=3000),其后有一行,包含n个正整数id(以空格分隔,0<id<1e9),为该学生的学号。接下来有t行,每行有两个正整数x,y,x为新队员的id,y为现有队员的id,将x插入到y的前面。 

Output

输出最终的队员信息表。

使用动态链表进行增查

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

typedef struct student{
	int id;
	struct student *next;
}stu;

typedef struct newStudent{
	int idnew;
	int idold;
}nstu;

//创建链表函数 
stu *Init_LinkList(int n){
	//创建头节点 
	stu *header=(stu*)malloc(sizeof(stu));
	header->id = 1;
	header->next = NULL;
	
	//尾部指针
	stu *pRear = header; 

	for(int i=0;i<n;i++){
		int val;
		scanf("%d", &val);
		
		//先创建新节点
		stu *newnode = (stu*)malloc(sizeof(stu));
		newnode->id = val;
		newnode->next = NULL;
		
		//新节点插入链表
		pRear->next = newnode;
		//局部指针将其所指节点中的next指针指向新的节点 
		
		//更新局部指针指向,让其指向新的节点 
		pRear = newnode;

	} 
	return header;
}

//链表插入函数 
void InsertByValue_LinkList(stu *header,int oldval,int newval){
	if(NULL==header){
		return;
	}
	
	//两个辅助指针变量
	stu *pPrev=header;
	stu *pCurrent =  pPrev->next;
	
	while(pCurrent != NULL){
		if(pCurrent->id==oldval){
			break;
		}
		pPrev=pCurrent;
		pCurrent= pCurrent->next;
	}
	
	//pCurrent为空,不存在这一节点 
	if (pCurrent==NULL){
		return; 
	}
	
	//创建新节点
	stu *newnode=(stu*)malloc(sizeof(stu));
	newnode->id=newval;
	newnode->next=NULL;
	
	//新节点插入到链表
	newnode->next=pCurrent;
	pPrev->next=newnode;
}

//遍历链表函数 
void Foreach_LinkList(stu *header){
	if (NULL==header){
		return;
	}
	
	//辅助指针变量 
	stu *pCurrent = header->next;
	
	while(pCurrent != NULL){
		if(pCurrent->next!=NULL)
			printf("%d ", pCurrent->id);
		else printf("%d", pCurrent->id);
		pCurrent=pCurrent->next;//指向下一个节点 
	}
}

//清空链表函数 
void Clear_LinkList(stu* header){
	if(NULL==header){
		return;
	}
	//要先用辅助指针保存要free的next指针
	
	stu *pCurrent=header->next;
	
	while(pCurrent!=NULL){
		//先保存下一节点地址
		stu *pNext=pCurrent->next;
		
		//释放当前节点内存
		free(pCurrent);
		
		//pCurrent指向下一节点
		pCurrent=pNext; 
	} 
	
	header->next=NULL;
}

int main(){
	int n,m;
	stu *header=(stu*)malloc(sizeof(stu));
	while(scanf("%d %d", &n, &m)!=EOF){
		header=Init_LinkList(n);
		
		nstu num[m];
		
		for(int i=0;i<m;i++){
			scanf("%d %d", &num[i].idnew, &num[i].idold);
		}
		
		for(int i=0;i<m;i++){
			InsertByValue_LinkList(header,num[i].idold,num[i].idnew);
		}
		
		Foreach_LinkList(header);
		Clear_LinkList(header);
		printf("\n");
	} 
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值