By 2017级计算机科学与技术专业 袁壮苗
题目描述
顺序表是我们数据结构中的基本储存形式,现在给定一个顺序表,有如下操作:
Insert X Y:在顺序表中X位置插入Y元素,遍历输出当前顺序表的所有元素。
Delete X:删除顺序表中的X元素,如果有多个X元素,只删除第一个X,遍历输出当前顺序的所有元素。
Locate X:输出顺序表中X元素的所在的位置,如果有多个X元素,只输出第一个X元素的位置。
GetElem X:输出顺序表中X位置上的元素。输入描述
多组测试数据。
对于每组测试数据,首先输入的是两个整数n,m(0<m<n<100),分别表示顺序表初始有n个元素,m次操作。
接下来是n个整数,表示顺序表中的n个元素。
然后是m次操作命令,命令是Insert X Y,Delete X,Locate X,GetElem X中的一种,其中的X,Y均为整数。输出描述
对于每组数据,输出有m行,对应m次操作:如果操作合法,则输出相应的结果。如果操作不合法,则输出"Wrong Input!"
输入样例
5 8 1 3 4 5 6 Insert 4 7 Insert 8 10 Delete 6 Delete 10 Locate 5 Locate 10 GetElem 3 GetElem 9输出样例
1 3 4 7 5 6 Wrong Input! 1 3 4 7 5 Wrong Input! 5 Wrong Input! 4 Wrong Input!提示
要求使用顺序表实现
#include<stdio.h>
#include<math.h>
#include<string.h>
#define long long LL
#define pi acos(-1.0)
#define mod 1000000008
int num[10000];
int My_Insert(int m, int n, int i)
{
int j,x,y;
if (m > i)
printf("Wrong Input!\n");
else
{
for (j = i; j >= m - 1; j--)
num[j + 1] = num[j];
num[m - 1] = n;
i++;
for(j=0;j<i-1;j++)
printf("%d ", num[j]);
printf("%d", num[i-1]);
putchar('\n');
}
return i;
}
int My_Delete(int m, int i) {
int j,x,y;
for (j = 0; j < i && num[j] != m; j++);
if (j == i)
printf("Wrong Input!\n");
else {
for (; j < i - 1; j++)
num[j] = num[j + 1];
i--;
printf("%d", num[0]);
for (j = 1; j < i; j++)
printf(" %d", num[j]);
putchar('\n');
}
return i;
}
int My_Locate(int m, int i)
{
int j,x,y;
for (j = 0; j < i && num[j] != m; j++);
if (j == i)
printf("Wrong Input!\n");
else
printf("%d\n", j + 1);
return 0;
}
int My_Getelem(int m, int i) {
if (m > i)
printf("Wrong Input!\n");
else printf("%d\n", num[m - 1]);
return 0;
}
int main()
{
int a,b,i,m,n,k,t,T;
char s[8];
scanf("%d %d", &a, &b);
for (i=0; i < a; i++)
scanf(" %d", &num[i]);
for (i=0; i<b; i++)
{
scanf(" %s", &s);
switch (s[0])
{
case 'D':
{
scanf("%d", &m);
a = My_Delete(m, a);
};
break;
case 'I':
{
scanf("%d %d", &m, &n);
a = My_Insert(m, n, a);
};
break;
case 'L':
{
scanf("%d", &m);
My_Locate(m, a);
};
break;
case 'G':
{
scanf("%d", &m);
My_Getelem(m, a);
}
}
}
}