原题链接:数据结构-链表的基本操作
解题思路:保存题解
注意事项:需要确保即使初始元素数量为 0,链表仍然有一个有效的头结点。这样可以避免在后续操作中因为 L 为 NULL 而导致的问题
参考代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node
{
int data;
struct node *next;
} node, *list;
#define OK 1
#define ERROR 0
// 在链表第x个位置插入元素e
int listinsert_l(list L, int x, int e)
{
if (x <= 0)
{
return ERROR;
}
list p = L;
int j = 0;
while (p != NULL && j < x - 1)
{
p = p->next;
j++;
}
if (!p)
{
return ERROR;
}
list s = (list)malloc(sizeof(node));
if (!s)
{
return ERROR;
}
s->data = e;
s->next = p->next;
p->next = s;
return OK;
}
// 删除链表第x个位置的元素
int listdelete_l(list L, int x)
{
if (x <= 0)
{
return ERROR;
}
list p = L;
int j = 0;
while (p != NULL && j < x - 1)
{
p = p->next;
j++;
}
if (!p || !p->next)
{
return ERROR;
}
list q = p->next;
p->next = q->next;
free(q);
return OK;
}
// 创建一个包含n个元素的链表
list createlist_l(int n)
{
list L = (list)malloc(sizeof(node)); // 头结点
if (!L)
{
return NULL;
}
L->next = NULL;
for (int i = 0; i < n; i++)
{
list p = (list)malloc(sizeof(node));
if (!p)
{
// 释放已分配的节点
list current = L->next;
while (current != NULL)
{
list next = current->next;
free(current);
current = next;
}
free(L);
return NULL;
}
scanf("%d", &p->data);
p->next = L->next;
L->next = p;
}
return L;
}
// 获取链表第x个位置的元素
int get_element(list L, int x)
{
if (x <= 0)
{
return ERROR;
}
list p = L->next;
int j = 1;
while (p != NULL && j < x)
{
p = p->next;
j++;
}
if (!p)
{
return ERROR;
}
printf("%d\n", p->data);
return OK;
}
// 显示链表的所有元素
void show_list(list L)
{
list p = L->next;
if (!p)
{
printf("Link list is empty\n");
return;
}
while (p)
{
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main()
{
int n, m, a, e;
char command[10];
list L;
scanf("%d", &n);
L = createlist_l(n);
scanf("%d", &m);
for (int i = 0; i < m; i++)
{
scanf("%s", command);
if (strcmp(command, "get") == 0)
{
scanf("%d", &a);
get_element(L, a);
}
else if (strcmp(command, "delete") == 0)
{
scanf("%d", &a);
if (listdelete_l(L, a) == OK)
{
printf("delete OK\n");
}
else
{
printf("delete fail\n");
}
}
else if (strcmp(command, "insert") == 0)
{
scanf("%d %d", &a, &e);
if (listinsert_l(L, a, e) == OK)
{
printf("insert OK\n");
}
else
{
printf("insert fail\n");
}
}
else if (strcmp(command, "show") == 0)
{
show_list(L);
}
else
{
printf("Unknown command\n");
}
}
// Free allocated memory
list current = L;
while (current != NULL)
{
list next = current->next;
free(current);
current = next;
}
return 0;
}0.0分
0 人评分
C语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程,并配有习题和答疑,点击了解:
一点编程也不会写的:零基础C语言学练课程
解决困扰你多年的C语言疑难杂症特性的C语言进阶课程
从零到写出一个爬虫的Python编程课程
只会语法写不出代码?手把手带你写100个编程真题的编程百练课程
信息学奥赛或C++选手的 必学C++课程
蓝桥杯ACM、信息学奥赛的必学课程:算法竞赛课入门课程
手把手讲解近五年真题的蓝桥杯辅导课程
发表评论 取消回复