#include <stdio.h>
#include<malloc.h>
#include<stdlib.h>
typedef struct node { // 节点结构
int score;
struct node *next;
} LinkList;
// 创建一个链表
LinkList *create (int n) {
LinkList *head, *node, *end; //定义头节点,普通节点,尾部节点;
head = (LinkList*)malloc(sizeof(LinkList)); //分配地址
end = head; //若是空链表则头尾节点一样
for (int i = 0; i < n; i++) {
node = (LinkList*) malloc(sizeof(LinkList));
node->score = rand();
end->next = node; // 当前节点的next
end = node; // 尾结点赋值
}
end->next = NULL; // 结束创建
return head;
}
// 修改某个节点
void change(LinkList *list,int n, int score) {//n为第n个节点
int i = 0;
while (i < n && list != NULL) {
list = list->next;
i++;
}
if (list != NULL) {
list->score = score;
printf("修改成功\n");
}
else {
printf("节点不存在\n");
}
}
// 删除某个节点
void delete(LinkList *list,int n) {//n为第n个节点
int i = 0;
LinkList *lastNode;
while (i < n && list != NULL) {
lastNode = list;
list = list->next;
i++;
}
if (list != NULL ) { // 寻找的节点存在
if (list->next != NULL) {
lastNode->next = list->next;
} else {
lastNode->next = NULL;
}
printf("删除成功\n");
}
else {
printf("节点不存在\n");
}
}
// 指定节点加入新节点
void insert(LinkList *list,int n, int score) {//n为第n个节点
int i = 0;
LinkList *lastNode;
while (i < n && list != NULL) {
lastNode = list;
list = list->next;
i++;
}
if (list != NULL ) { // 寻找的节点存在
LinkList *node; //定义头节点,普通节点,尾部节点;
node = (LinkList*)malloc(sizeof(LinkList)); //分配地址
node->score = score;
lastNode->next = node;
node->next = list;
printf("节点插入成功\n");
}
else {
printf("节点不存在\n");
}
}
void traverse (LinkList *list) {
while (list->next != NULL) {
list = list->next;
printf("%d \n", list->score);
}
// 遍历结束
printf("遍历结束\n");
}
int main()
{
// 创建链表test
LinkList *list = create(10);
traverse(list);
// modify
change(list, 2, 666);
traverse(list);
// delete
delete(list, 10);
traverse(list);
insert(list, 2, 777);
traverse(list);
}
网友评论