问题 D: 链表查找(线性表)
时间限制: 1 Sec 内存限制: 128 MB
提交: 39 解决: 35
题目描述
线性表(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
经验总结
emmmmm,按照题目意思来就行啦~( •̀∀•́ )
正确代码
#include <cstdio>
struct node
{
int data;
node * next;
};
int main()
{
int m,n;
while(~scanf("%d",&m))
{
scanf("%d",&n);
node * L=new node;
L->next=NULL;
node * p=L;
for(int i=0;i<n;i++)
{
node * temp=new node;
scanf("%d",&temp->data);
temp->next=NULL;
p->next=temp;
p=p->next;
}
node * pre=L;
p=L->next;
while(p->data<m)
{
pre=p;
p=p->next;
}
if(p->data==m)
{
printf("%d\n",m);
node * s=p->next;
pre->next=s;
p->next=s->next;
s->next=p;
}
else
{
printf("no\n");
node * temp=new node;
temp->data=m;
temp->next=p;
pre->next=temp;
}
p=L->next;
while(p!=NULL)
{
printf("%d ",p->data);
p=p->next;
}
printf("\n");
}
return 0;
}