师--链表的结点插入
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
给出一个只有头指针的链表和 n 次操作,每次操作为在链表的第 m 个元素后面插入一个新元素x。若m 大于链表的元素总数则将x放在链表的最后。
Input
多组输入。每组数据首先输入一个整数n(n∈[1,100]),代表有n次操作。
接下来的n行,每行有两个整数Mi(Mi∈[0,10000]),Xi。
Output
对于每组数据。从前到后输出链表的所有元素,两个元素之间用空格隔开。
Sample Input
4 1 1 1 2 0 3 100 4
Sample Output
3 1 2 4
此题我共写过两种方法,方法的主要差别是查找的过程。
方法一:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node * head_creat();
void insert_node(struct node *, int, int);
void output_list(struct node *);
int main()
{
int n, m, x;
struct node *head;
while(~scanf("%d", &n))///注意本题是多组输入!!!找了很久没找到的错误
{
head = head_creat();
while(n--)
{
scanf("%d %d", &m, &x);
insert_node(head, m, x);
}
output_list(head);///n 为 0 时输出本组数据组成的链表
}
return 0;
}
struct node *head_creat()
{
struct node *head;
head = (struct node *)malloc(sizeof(struct node));
head->next = NULL;
return head;
}
void insert_node(struct node *head, int m, int x)
{
int i;
struct node *p, *q;///p 作为前驱结点,用于观察控制结点位置及插入结点
p = head;
for(i = 1; i <= m; i++)///找到第 m 个元素结点, 令 p 指向此节点
{
if(p->next != NULL)
p = p->next;
///当 p 未指向尾结点时,直到找到第 m 个元素或超出链表长度时才退出循环
else
break;///当 p 指向尾结点时,直接退出循环
}/// 下方为:顺序插入结点的操作
q = (struct node *)malloc(sizeof(struct node));///创建一个结点并令 q 指向它
q->data = x;///为 q 所指向的结点数据域赋值
q->next = p->next;///令 q 的指针域指向 p 的指针域所指向的结点
p->next = q;///令 p 的指针域指向 q, 结点插入完成
}
void output_list(struct node *head)
{
struct node *p;
p = head->next;
while(p)
{
if(p == head->next)
printf("%d", p->data);
else
printf(" %d", p->data);
p = p->next;
}
printf("\n");
}
方法二:
#include <bits/stdc++.h>
struct node
{
int data;
struct node *next;
};
using namespace std;
struct node * sequence_Linked_List();
void insert_node(struct node *, int);
void output_List(struct node *);
int main()
{
int n;
while(cin >> n)///注意本题是多组输入!!!找了很久没找到的错误
{
struct node *head;
head = sequence_Linked_List();
insert_node(head, n);
output_List(head);
}
return 0;
}
struct node *sequence_Linked_List()
{
struct node *head;
head = (struct node *)malloc(sizeof(struct node));
head->next = NULL;
return head;
};
void insert_node(struct node *head, int n)
{
int m, x, i;
struct node *q, *p;
while(n--)
{
cin >> m >> x;
q = head;///每次插入开始都要重置 指针q
i = 0;///重置 i
p = (struct node *)malloc(sizeof(struct node));
p->data = x;///将需要插入的元素先存起来
p->next = NULL;
while(q->next)///当 q 为尾结点时退出查找
{
///查找到第 m 个元素结点
if(i == m)
{
///当 i = m 时将 p 插入,并结束此次查找
p->next = q->next;
q->next = p;
break;
}
else
{
q = q->next;
i++;
}
}
if(q->next == NULL)
{
///如果 q->next 为空,则此次查找已经查找到链表尾,即 m 大于等于结点数
q->next = p;
}
}
}
void output_List(struct node *head)
{
struct node *p;
p = head->next;
while(p)
{
if(p == head->next)
cout << p->data;
else
printf(" %d", p->data);
p = p->next;
}
cout << endl;
}