线性表链式存储实现方法
输入
输入第1行是一个整数n,表示之后还有n行输入。每行输入表示对线性表的一条操作指令,格式是“指令编号 参数1 参数2(如有)”。指令编号为1,表示Insert操作,此时参数1为插入的元素值,参数2为所插入元素在线性表中的位序。指令编号为2,表示Delete操作,此时只有一个参数,即待删除元素在线性表中的位序。
输出
输入例1
5
1 10 1
1 20 2
1 30 3
1 40 1
1 50 2
输出例1
40 50 10 20 30
输入例2
10
1 10 2
1 20 1
1 30 2
1 40 3
1 50 4
2 5
2 3
1 60 1
1 70 1
2 6
输出例2
70 60 20 30 50
代码示例
#include<stdio.h>
#include<stdlib.h>
typedef struct node* list;//结构体
struct node
{
int data;
list next;
};
//初始化
list makeempty() {
list L;
L = (list)malloc(sizeof(struct node));
L->next = NULL;
return L;
}
//插入
list insert(list L, int x, int i) {
list p, pre;
int cnt = 0;
pre = L;
while (pre && cnt <i - 1) {
pre = pre->next;
cnt++;
}
if (cnt == i - 1&&pre)
{
p = (list)malloc(sizeof(struct node));
p->data = x;
p->next = pre->next;
pre->next = p;
}
return L;
}
//删除
list Delete(list L, int i) {
list p, pre;
int cnt = 0;
pre = L;
while (pre && cnt < i - 1) {
pre = pre->next;
cnt++;
}
if (pre && cnt == i-1&&pre->next) {//注意!!pre->next是为了保证p存在
p = pre->next;
pre->next = p->next;
free(p);
}
return L;
}
int main() {
int n, op, i, x;
list L,q;
L = makeempty();
scanf_s("%d", &n);
while (n--) {
scanf_s("%d", &op);
switch (op) {
case 1:scanf_s("%d %d", &x, &i);
insert(L, x, i);
break;
case 2:scanf_s("%d", &i);
L=Delete(L, i);
break;
}
}
q = L->next;//不能直接用L否则会出现乱码
while (q) {
printf("%d ", q->data);
q = q->next;
}
return 0;
}