输入格式

第一行输入为一个正整数 m(1≤m≤100),代表一共有 m 个操作。

接下来一共输入 m 行,每行首先输入一个整数 t,代表着以下几种操作:

t=1,代表执行插入操作,此时还需输入两个整数 a 和 b(0≤a,b≤100),代表在位置 a 上插入值为 b 的元素,成功插入输出success,否则输出failed。
t=2,代表执行遍历操作,此时程序顺序输出链表的所有元素。 t=3,代表执行删除操作,此时还需输入一个整数 a(0≤a≤100),表示删除位置 a 上的元素,如果成功删除则输出success,否则输出failed。
t=4,代表执行反转链表的操作,在执行了反转操作之后,还会有其他的操作来验证你的程序是否正确的完成了链表的反转。

输出格式

输出的结果取决于每组输入的数据。在遍历输出链表时,每个元素后面跟一个空格。对于操作 1 和操作 3,操作成功输出success,否则输出failed。每次操作的输出各占一行。

#include <stdio.h>
#include <stdlib.h>

typedef struct Node{
int data;
struct Node *next;
}Node, *LinkedList;

LinkedList insert(LinkedList head, Node *node, int index) {
if (head == NULL) {
if (index != 0) {
printf("failed\n");
return head;
}
head = node;
printf("success\n");
return head;
}
if (index == 0) {
node->next = head;
head = node;
printf("success\n");
return head;
}
Node *current_node = head;
int count = 0;
while (current_node->next != NULL && count < index - 1) {
current_node = current_node->next;
count++;
}
if (count == index - 1) {
node->next = current_node->next;
current_node->next = node;
printf("success\n");
return head;
}
printf("failed\n");
return head;
}

void output(LinkedList head) {
if (head == NULL) {
return;
}
Node *current_node = head;
while (current_node != NULL) {
printf("%d ", current_node->data);
current_node = current_node->next;
}
printf("\n");
}

LinkedList delete_node(LinkedList head, int index) {
if (head == NULL) {
printf("failed\n");
return head;
}
Node *current_node = head;
int count = 0;
if (index == 0) {
head = head->next;
free(current_node);
printf("success\n");
return head;
}
while(current_node->next != NULL && count < index - 1) {
current_node = current_node->next;
count++;
}
if (current_node->next != NULL && count == index - 1) {
Node *delete_node = current_node->next;
current_node->next = delete_node->next;
free(delete_node);
printf("success\n");
return head;
}
printf("failed\n");
return head;
}

LinkedList reverse(LinkedList head) {
if (head == NULL) {
return head;
}
Node *current_node, *next_node;
current_node = head->next;
head->next = NULL;
while (current_node != NULL){
next_node = current_node->next;
current_node->next = head;
head = current_node;
current_node = next_node;
}
return head;
}

void clear(LinkedList head) {
Node *current_node = head;
while (current_node != NULL) {
Node *delete_node = current_node;
current_node = current_node->next;
free(delete_node);
}
}

int main() {
LinkedList linkedlist = NULL;
int m,t;
int value,index;
scanf("%d",&m);
for (int i = 0; i < m; i++) {
scanf("%d",&t);
if (t == 1) {
scanf("%d%d",&index,&value);
Node *node = (Node *)malloc(sizeof(Node));
node->data = value;
node->next = NULL;
linkedlist = insert(linkedlist,node,index);
}
if (t == 2){
output(linkedlist);
}
if (t == 3) {
scanf("%d",&index);
linkedlist = delete_node(linkedlist,index);
}
if (t == 4) {
linkedlist = reverse(linkedlist);
}
}
return 0;
}