输入文件的第一行有两个整数n,q,分别表示初始链表中元素个数和对链表操作的次数,第二行有
n个整数,表示初始链表的元素,保证这些数字不超过int表示的范围。
接下来q行,每行可能为如下两个操作之一:
1 a b表示在第a个元素后面插入值为b的元素,
2 a表示将链表中第a个元素删除,如果a大于当时链表长度,则忽略此操作
如:
输入
3 3
1 2 3
1 1 4
1 2 5
2 2
输出(每个元素后面需要跟一个空格)
1 5 2 3
#include<stdio.h>
#include<stdlib.h>
struct node {
int data;
struct node *next;
};
struct node *head,*tail,*node;
struct node *create_linklist(int n)
{
head = (struct node *)malloc(sizeof(struct node));
tail = head;
for (int i = 0; i < n; i++) {
node = (struct node *)malloc(sizeof(struct node));
scanf("%d",&node->data);
tail->next = node;
tail = node;
}
tail->next = NULL;
return head;
}
void insert_node(int pos, int data)
{
struct node *pre;
pre = head;
int i = 0;
struct node *p = (struct node *)malloc(sizeof(struct node));
if (pos == 0) {
p->data = data;
p->next = head;
head = p;
} else {
while (i < pos) {
pre = pre->next;
i++;
}
p->data = data;
p->next = pre->next;
pre->next = p;
if (tail->next == NULL)
tail = p;
}
}
void delete_node(int pos)
{
struct node *pre, *p;
pre = head;
int i = 0;
if (pos == 0) {
head = head->next;
free(pre);
} else {
while (i < pos -1) {
pre = pre->next;
i++;
}
p = pre->next;
pre->next = p->next;
if (p->next == NULL)
tail = pre;
free(p);
}
}
void print_linklist(void)
{
struct node *p;
p = head;
while (p->next) {
p = p->next;
printf("%d ", p->data);
}
if (p == NULL)
printf(" ");
}
int main(int argc, char *argv[])
{
int n, q;
scanf("%d %d", &n, &q);
head = create_linklist(n);
int flag, pos, data;
for (int i = 0; i < q; i++) {
scanf("%d", &flag);
if (flag == 1) {
scanf("%d%d", &pos, &data);
insert_node(pos, data);
} else {
delete_node(pos);
}
}
print_linklist();
return 0;
}