解题思路:
注意事项:
初始列表插入时顺序相反,且无"insert OK"提示,加入flag判断是否为初始列表操作;
参考代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.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 position, int element,int flag) {
Node* newNode = createNode(element);
if (position == 1) {
newNode->next = *head;
*head = newNode;
} else {
Node* current = *head;
int count = 1;
while (count < position - 1 && current != NULL) {
current = current->next;
count++;
}
if (current == NULL) {
printf("insert fail\n");
return;
}
newNode->next = current->next;
current->next = newNode;
}
if(flag) printf("insert OK\n");
}
void delete(Node** head, int position) {
if (*head == NULL) {
printf("delete fail\n");
return;
}
Node* temp = *head;
if (position == 1) {
*head = temp->next;
free(temp);
} else {
Node* current = *head;
int count = 1;
while (count < position && current != NULL) {
temp = current;
current = current->next;
count++;
}
if (current == NULL) {
printf("delete fail\n");
return;
}
temp->next = current->next;
free(current);
}
printf("delete OK\n");
}
int get(Node* head, int position) {
Node* current = head;
int count = 1;
while (count < position && current != NULL) {
current = current->next;
count++;
}
if (current == NULL) {
printf("get fail\n");
return -1;
}
return current->data;
}
void show(Node* head) {
if (head == NULL) {
printf("Link list is empty\n");
return;
}
Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
int n, m;
scanf("%d", &n);
Node* head = NULL;
for (int i = 0; i < n; i++) {
int data;
scanf("%d", &data);
insert(&head, 1, data,0);
}
scanf("%d", &m);
for (int i = 0; i < m; i++) {
char operation[10];
scanf("%s", operation);
if (strcmp(operation, "get") == 0) {
int position;
scanf("%d", &position);
int result = get(head, position);
if (result != -1) {
printf("%d\n", result);
}
} else if (strcmp(operation, "insert") == 0) {
int position, element;
scanf("%d %d", &position, &element);
insert(&head, position, element,1);
} else if (strcmp(operation, "delete") == 0) {
int position;
scanf("%d", &position);
delete(&head, position);
} else if (strcmp(operation, "show") == 0) {
show(head);
}
}
return 0;
}
0.0分
0 人评分