题目描述
线性表(a1,a2,a3,…,an)中元素递增有序且按顺序存储于计算机内。要求设计一算法完成:
(1) 用最少时间在表中查找数值为x的元素。
(2) 若找到将其与后继元素位置相交换。
(3) 若找不到将其插入表中并使表中元素仍递增有序。
输入
输入:x=3
输入长度:9
输入数据:2 3 5 7 12 15 17 23 45
输出
相同元素为:3
交换后的链表为:2 5 3 7 12 15 17 23 45
样例输入
4 9 2 3 5 7 12 15 17 23 45
样例输出
no 2 3 4 5 7 12 15 17 23 45
#include <cstdio>
struct node{
int data;
node *next;
};
void creat(node *l,int n){
node *p=l;
for(int i=0;i<n;i++){
node *temp=new node;
temp->next =NULL;
scanf("%d",&temp->data );
p->next =temp;
p=temp;
}
}
void print(node *l){
node *p=l;
while(p->next!=NULL){
printf("%d ",p->next->data);
p=p->next ;
}
delete(p);
}
void search(node *l,int x){
node *p=l;
while(p->next!=NULL&&p->next->data<x){
p=p->next;
}
if(p->next->data ==x){
node *temp1=p->next,*temp2=temp1->next ;
temp1->next =temp2->next;
temp2->next =temp1;
p->next=temp2;
printf("%d\n",x) ;
print(l);
}else{
node *temp=new node;
temp->data =x;
temp->next =p->next ;
p->next =temp;
printf("no\n");
print(l);
}
}
int main(){
int x,m;
scanf("%d%d",&x,&m);
node *l=new node;
l->next =NULL;
creat(l,m);
search(l,x);
return 0;
}