输入第1行是一个整数n,表示之后还有n行输入。
每行输入表示对线性表的一条操作指令,格式是“指令编号 参数1 参数2(如有)”。
指令编号为1,表示Insert操作,此时参数1为插入的元素值,参数2为所插入元素在线性表中的位序。
指令编号为2,表示Delete操作,此时只有一个参数,即待删除元素在线性表中的位序。
指令编号为3,表示Find操作,此时只有一个参数,即待查元素的值。
顺序存储:
#include <iostream>
using namespace std;
const int maxn = 1e4 + 1;
struct Node {
int data[maxn];
int last;
};
typedef struct Node* List;
List MakeEmpty() {
List L = (struct Node*)malloc(sizeof(struct Node));
L->last = -1;
return L;
}
void Insert(List L, int val, int sernum) {
if (sernum<1 || sernum>L->last + 2) {
//不合法
return;
}
for (int j = L->last; j >= sernum - 1; j--) {
L->data[j + 1] = L->data[j];
}
L->data[sernum - 1] = val;
L->last++;
return;
}
void Delete(List L, int sernum) {
if (sernum<1 || sernum>L->last + 1) {
//不合法
return;
}
for (int j = sernum; j <= L->last; j++) {
L->data[j - 1] = L->data[j];
}
L->last--;
return;
}
int Find(List L, int val) {
int i = 0;
while (i <= L->last && L->data[i] != val)
i++;
if (i > L->last)
return -1;
else
return i;
}
int main() {
int n, x, val, sernum;
cin >> n;
List L = MakeEmpty();
for (int i = 0; i < n; i++) {
cin >> x;
if (x == 1) {
cin >> val >> sernum;
Insert(L, val, sernum);
}
else if (x == 2) {
cin >> sernum;
Delete(L, sernum);
}
else {
cin >> val;
cout << Find(L, val) << endl;
}
}
for (int i = 0; i <= L->last; i++) {
cout << L->data[i] << ' ';
}
return 0;
}
链式存储:
#include <iostream>
using namespace std;
const int maxn = 1e4 + 1;
struct Node {
int data;
struct Node* next;
};
typedef struct Node* List;
List creatlist() {
struct Node* headnode = (struct Node*)malloc(sizeof(struct Node));
headnode->next = NULL;
return headnode;
}
void Insect(List L, int val, int sernum) {
List tmp, pre;
int cnt = 0;
pre = L;
while (pre && cnt < sernum - 1) {
pre = pre->next;
cnt++;
}
if (pre == NULL || cnt != sernum - 1) {
//非法插入
return;
}
else {
tmp = (struct Node*)malloc(sizeof(struct Node));
tmp->data = val;
tmp->next = pre->next;
pre->next = tmp;
return;
}
}
void Delete(List L, int sernum) {
List pre, tmp;
int cnt = 0;
pre = L;
while (pre && cnt < sernum - 1) {
pre = pre->next;
cnt++;
}
if (pre == NULL || cnt != sernum - 1 || pre->next == NULL) {
//节点找不到
return;
}
else {
tmp = pre->next;
pre->next = tmp->next;
free(tmp);
return;
}
}
void Find(List L, int val) {
List pre, tmp;
pre = L;
int cnt = 0;
while (pre && pre->data != val) {
pre = pre->next;
cnt++;
}
if (pre == NULL) {
cout << -1 << endl;
return;
}
else
{
cout << cnt << endl;
return;
}
}
int main() {
int x, n, val, sernum;
List L;
L = creatlist();
cin >> n;
for (int i = 0; i < n; i++) {
cin >> x;
if (x == 1) {
cin >> val >> sernum;
Insect(L, val, sernum);
}
else if(x==2){
cin >> sernum;
Delete(L, sernum);
}
else if (x == 3) {
cin >> val;
Find(L, val);
}
}
List p = L->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
return 0;
}