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;
}