解题思路:
这道题要求在线性表上进行操作,我们可以使用顺序表或者链表,因为比较熟悉链表,我们以链表为例,之后也有用数组实现的简易方法。
已知线性表为递增序且知道内容与元素个数,我们需要进行一次遍历并新元素插入即可。
创建和输出链表没什么特别的,就是插入时要关注一下边界点的完善。
具体操作见代码,代码中有部分注释。
题解代码:
链表实现:
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int data;
struct node *next;
}Node;
void CreatList(Node *head,int n){//创建链表
Node *p;
p = (Node*)malloc(sizeof(Node));
p = head;
for(int i=0;i<n;i++){
p->next = (Node*)malloc(sizeof(Node));
scanf("%d",&p->next->data);
p = p->next;
}
p->next = NULL;
}
void Insert(Node *head,int x){//插入链表函数
Node *p,*px;
p = head;
px = (Node*)malloc(sizeof(Node));
px->data = x;
while(p->next){
if(p->next->data>=px->data){
px->next = p->next;
p->next = px;
return;
}
else{
p = p->next;
}
}
p->next = px;
px->next = NULL;
}
void OutputList(Node *head){//输出链表
Node *p = head->next;
while(p){
printf("%d ",p->data);
p = p->next;
}
}
int main()
{
int n,x;
scanf("%d",&n);
Node *head;
head = (Node*)malloc(sizeof(Node));
CreatList(head,n);
scanf("%d",&x);
Insert(head,x);
OutputList(head);
return 0;
}
数组实现:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int A[1000];
int i,j,n,x;
scanf("%d\n",&n);
for(i=0;i<n;i++){//生成顺序表
scanf("%d",&A[i]);
}
scanf("%d",&x);
for(i=0;i<n;i++){//遍历数组插入元素
if(x<=A[i]){
break;
}
}
for(j=n;j>i;j--){//需要将大于目标值的数组元素全部右移1位(这也是本题用数组作为储存结构的缺陷)
A[j]=A[j-1];
}
A[i]=x;
for(i=0;i<=n;i++){
printf("%d ",A[i]);
}
return 0;
}