输入数据只有一组,第一行有n+1个整数,第一个整数是这行余下的整数数目n,后面是n个整数。这一行整数是用来初始化列表的,并且输入的顺序与列表中的顺序相反,也就是说如果列表中是1、2、3那么输入的顺序是3、2、1。 第二行有一个整数m,代表下面还有m行。每行有一个字符串,字符串是“get”,“insert”,“delete”,“show”中的一种。如果是“get”或者“delete”,则其后跟着一个整数a,代表获得或者删除第a个元素;如果是“insert”,则其后跟着两个整数a和e,代表在第a个位置前面插入e;“show”之后没有整数。 Output 如果获取成功,则输出该元素;如果删除成功则输出“delete OK”;如果获取失败或者删除失败,则输出“get fail”以及“delete fail”。如果插入成功则输出“insert OK”,否则输出“insert fail”。如果是“show”则输出列表中的所有元素,如果列表是空的,则输出“Link list is empty”。注:所有的双引号均不输出。请用C语言写
时间: 2023-05-31 13:04:32 浏览: 100
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node* next;
} Node;
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
void insert(Node** head, int pos, int data) {
if (pos == 1) {
Node* newNode = createNode(data);
newNode->next = *head;
*head = newNode;
printf("insert OK\n");
return;
}
Node* prev = NULL;
Node* curr = *head;
int i;
for (i = 1; i < pos && curr != NULL; i++) {
prev = curr;
curr = curr->next;
}
if (curr != NULL) {
Node* newNode = createNode(data);
prev->next = newNode;
newNode->next = curr;
printf("insert OK\n");
} else {
printf("insert fail\n");
}
}
void delete(Node** head, int pos) {
if (pos == 1) {
Node* temp = *head;
*head = (*head)->next;
free(temp);
printf("delete OK\n");
return;
}
Node* prev = NULL;
Node* curr = *head;
int i;
for (i = 1; i < pos && curr != NULL; i++) {
prev = curr;
curr = curr->next;
}
if (curr != NULL) {
prev->next = curr->next;
free(curr);
printf("delete OK\n");
} else {
printf("delete fail\n");
}
}
void get(Node* head, int pos) {
Node* curr = head;
int i;
for (i = 1; i < pos && curr != NULL; i++) {
curr = curr->next;
}
if (curr != NULL) {
printf("%d\n", curr->data);
} else {
printf("get fail\n");
}
}
void show(Node* head) {
if (head == NULL) {
printf("Link list is empty\n");
return;
}
Node* curr = head;
while (curr != NULL) {
printf("%d ", curr->data);
curr = curr->next;
}
printf("\n");
}
int main() {
int n, m, i;
scanf("%d", &n);
Node* head = NULL;
for (i = 0; i < n; i++) {
int data;
scanf("%d", &data);
Node* newNode = createNode(data);
newNode->next = head;
head = newNode;
}
scanf("%d", &m);
for (i = 0; i < m; i++) {
char op[10];
int pos, data;
scanf("%s", op);
if (strcmp(op, "get") == 0) {
scanf("%d", &pos);
get(head, pos);
} else if (strcmp(op, "insert") == 0) {
scanf("%d%d", &pos, &data);
insert(&head, pos, data);
} else if (strcmp(op, "delete") == 0) {
scanf("%d", &pos);
delete(&head, pos);
} else if (strcmp(op, "show") == 0) {
show(head);
}
}
return 0;
}
阅读全文