问题遇到的现象和发生背景
问题相关代码,请勿粘贴截图
运行结果及报错内容
我的解答思路和尝试过的方法
我想要达到的结果
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct LNode {
int date;
struct LNode *next;
} Node;
#define len sizeof(Node)
Node *creat(int n);
void output(Node *begin);
void get(Node *begin, int n);
Node *insert(Node *begin, int n, int x);
Node *delet(Node *begin, int n);
int main() {
int n, ret, x, i;
char ch[4][20] = {{"show"}, {"delete"}, {"insert"}, {"get"}};
char str[20];
scanf("%d", &n);
Node *begin;
begin = creat(n);
int count;
scanf("%d", &count);
while (count) {
scanf("%s", str);
for (i = 0; i < 4; i++)
if (strcmp(ch[i], str) == 0)
break;
switch (i) {
case 0:
output(begin);
break;
case 1:
scanf("%d", &n);
begin = delet(begin, n);
break;
case 2:
scanf("%d%d", &n, &x);
begin = insert(begin, n, x);
break;
case 3:
scanf("%d", &n);
get(begin, n);
break;
}
count--;
}
return 0;
}
Node *creat(int n) {
int count = 0;
Node *p1, *p2;
p2 = malloc(len);
p2->next = NULL;
while (n) {
p1 = malloc(len);
scanf("%d", &p1->date);
p1->next = p2->next;
p2->next = p1;
n--;
}
return p1;
}
void output(Node *begin) {
Node *p1 = begin;
int flag = 0;
while (p1) {
printf("%d ", p1->date);
p1 = p1->next;
flag = 1;
}
if (flag == 0)
printf("Link list is empty\n");
else
putchar('\n');
}
void get(Node *begin, int n) {
Node *p1;
p1 = begin;
int i = 0;
while (i < n - 1 && p1) {
p1 = p1->next;
i++;
}
if (i > n || p1 == NULL)
printf("get fail\n");
else
printf("%d\n", p1->date);
}
Node *insert(Node *begin, int n, int x) {
Node *front = NULL, *head, *move, *temp;
head = move = begin;
int i = 0;
while (i < n - 1 && move->next) {
front = move;
move = move->next;
i++;
}
if (move == NULL) {
head = malloc(len);
head->date = x;
head->next = NULL;
}
if (move) {
if (front == NULL) {
head = temp = malloc(len);
temp->date = x;
temp->next = move;
} else {
temp = malloc(len);
temp->date = x;
front->next = temp;
temp->next = move;
}
}
return head;
}
Node *delet(Node *begin, int n) {
Node *front = NULL, *move = begin, *head = begin;
int i = 0, flag = 0;
move = begin;
while (i < n - 1 && move) {
front = move;
move = move->next;
i++;
}
if (move == head && move) {
head = head->next;
flag = 1;
} else if (move) {
front->next = move->next;
flag = 1;
}
if (flag)
printf("delete OK\n");
else
printf("delete fail\n");
return head;
}