解题思路:
注意事项:
初始列表插入时顺序相反,且无"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 人评分
汽水瓶 (C语言代码)浏览:698 |
C语言训练-求s=a+aa+aaa+aaaa+aa...a的值 (C++代码)(手动优化一下计算)浏览:1283 |
母牛的故事 (C语言代码)浏览:435 |
计算质因子 (C++代码)浏览:1630 |
简单的a+b (C语言代码)浏览:573 |
WU-拆分位数 (C++代码)浏览:779 |
C语言程序设计教程(第三版)课后习题6.9 (C语言代码)浏览:632 |
C语言程序设计教程(第三版)课后习题5.4 (C语言代码)浏览:780 |
C语言程序设计教程(第三版)课后习题5.6 (C语言代码)浏览:558 |
交换Easy (C语言代码)浏览:761 |