题目描述
线性表(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
在deal函数中,不能先判断now->next!==NULL,因为此时now可能为null,再访问其next,会导致程序错误。
#include<stdio.h>
#include<stdlib.h>
#include<algorithm>
#include<string.h>
using namespace std;
struct node
{
int data;
node *next;
};
void deal(node *&head, int x)
{
node *now = head->next;
while(now != NULL)
{
if(now->data==x)
{
printf("yes\n");
break;
}
else
now = now -> next;
}
// printf("%d\n",now->data);
if(now==NULL)//此处和else if判断顺序不能改变
{
node *p = head;
while(p->next->data < x)
{
p = p->next;
}
node *a;
a = new node;
a->data = x;
a->next = p->next;
p->next = a;
printf("no\n");
}
else if(now->next!=NULL)
{
int temp;
temp = now->data;
now->data = now->next->data;
now->next->data = temp;
}
node *b = head->next;
while(b!=NULL)
{
printf("%d", b->data);
if(b->next!=NULL)
printf(" ");
else
printf("\n");
b = b->next;
}
}
int main()
{
int x;
while(scanf("%d",&x)!=EOF)
{
int n;
scanf("%d",&n);
node *head, *now, *p;
head = new node;
head->next = NULL;
p = head;
int t;
for(int i=0; i<n; i++)
{
scanf("%d",&t);
now = new node;
now->data = t;
now->next = NULL;
p->next = now;
p = now;
}
deal(head, x);
}
return 0;
}