1.知识点:链表的查询、插入、输出
2.题意:给出一个只有头指针的链表和 n 次操作,每次操作为在链表的第 m 个元素后面插入一个新元素x。若m 大于链表的元素总数则将x放在链表的最后
3.注意事项:注意当m大于当前链表元素总数的情况
代码:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int Data;
struct node *next;
}*head;
void Insert(int m, int x);//链表元素插入
void Pri(struct node *h);//链表元素输出
int main()
{
int n, m, x;
while(scanf("%d", &n) != EOF)
{
head = (struct node *)malloc(sizeof(struct node));
head->next = NULL;
while(n--)
{
scanf("%d %d", &m, &x);
Insert(m, x);//插入操作
}
Pri(head);//输出操作
}
return 0;
}
void Pri(struct node *h)//链表元素输出函数
{
struct node *p;
p = h->next;
while(p != NULL)
{
printf("%d%c", p->Data, p ->next == NULL? '\n': ' ');
p = p->next;
}
}
void Insert(int m, int x)//链表元素插入函数
{
int cnt = 0;
int flag = 0;//判断元素是否插入(判断插入元素位置)
struct node *p, *q;
q = (struct node *)malloc(sizeof(struct node));
q->Data = x;
p = head;
while(p->next != NULL)
{
if(cnt == m)
{
flag = 1;
q->next = p->next;
p->next = q;
}
cnt++;//寻找插入位置
p = p->next;//寻找插入位置
}
if(flag == 0)//(链表只有头结点)||(m大于等于链表的元素总数)
{
q->next = p->next;
p->next = q;
}
}