7-8 双链表
作者 hyt
单位 郑州航空工业管理学院
实现一个双链表,双链表初始为空,支持 5 种操作:
1.在最左侧插入一个数;
2.在最右侧插入一个数;
3.将第 k 个插入的数删除;
4.在第 k 个插入的数左侧插入一个数;
5.在第 k 个插入的数右侧插入一个数
现在要对该链表进行 M 次操作,进行完所有操作后,从左到右输出整个链表。
注意:题目中第 k 个插入的数并不是指当前链表的第 k 个数。例如操作过程中一共插入了 n 个数,则按照插入的时间顺序,这 n 个数依次为:第 1 个插入的数,第 2 个插入的数,…第 n 个插入的数。
输入格式:
第一行包含整数 M,表示操作次数。
接下来 M 行,每行包含一个操作命令,操作命令可能为以下几种:
1.L x,表示在链表的最左端插入数 x。
2.R x,表示在链表的最右端插入数 x。
3.D k,表示将第 k 个插入的数删除。
4.IL k x,表示在第 k 个插入的数左侧插入一个数。
5.IR k x,表示在第 k 个插入的数右侧插入一个数。
输出格式:
共一行,将整个链表从左到右输出。
数据范围:
1≤M≤100000
所有操作保证合法。
输入样例:
在这里给出一组输入。例如:
10
R 7
D 1
L 3
IL 2 10
D 3
IL 2 7
L 8
R 9
IL 4 7
IR 2 2
输出样例:
在这里给出相应的输出。例如:
8 7 7 3 2 9
代码如下:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct note
{
int x;
struct note *fwd;
struct note *bwd;
int id;
} note;
// 头尾节点初始化;
note head = {0, NULL, NULL,0};
note tail = {0, NULL, NULL,0};
int id = 1;//标记操作
void op(char *s);
note *find(int k);
void print();
void link(note *a,note *b,note *in);
int main()
{
head.bwd = NULL;
tail.fwd = NULL;
head.fwd = &tail;
tail.bwd = &head;
int m;
scanf("%d", &m);
for (int o = 1; o <= m; o++)
{
char s[3];
scanf("%s", s);
op(s);
}
print();
}
note *find(int k)
{
note *p = head.fwd;
while (p->id != k)
{
p = p->fwd;
}
return p;
}
void link(note *a,note *b,note *in)
{
in->bwd=a;
in->fwd=b;
b->bwd=in;
a->fwd=in;
}
void op(char *s)
{
if (strcmp(s, "R") == 0)
{
int x;
scanf("%d", &x);
// 初始化要插入的节点
note *m = (note *)malloc(sizeof(note));
m->x = x;
m->id = id;
id++;
// 插入到尾
link(tail.bwd,&tail,m);
}
else if (strcmp(s, "L") == 0)
{
int x;
scanf("%d", &x);
// 初始化要插入的节点
note *m = (note *)malloc(sizeof(note));
m->x = x;
m->id = id;
id++;
// 插入到头
link(&head,head.fwd,m);
}
else if (strcmp(s, "D") == 0)
{
int k;
scanf("%d", &k);
note *p = find(k);
p->bwd->fwd = p->fwd;
p->fwd->bwd = p->bwd;
free(p);
}
else if (strcmp(s, "IL") == 0)
{
int k, x;
scanf("%d %d", &k, &x);
note *p = find(k);
//
note *m = (note *)malloc(sizeof(note));
m->x = x;
m->id = id;
id++;
//
link(p->bwd,p,m);
}
else if (strcmp(s, "IR") == 0)
{
int k, x;
scanf("%d %d", &k, &x);
note *p = find(k);
//
note *m = (note *)malloc(sizeof(note));
m->x = x;
m->id = id;
id++;
//
link(p,p->fwd,m);
}
}
void print()
{
note *p = head.fwd;
while (p->fwd != NULL)
{
printf("%d ", p->x);
p = p->fwd;
}
printf("\n");
}