#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int val;
struct Node* next;
}M;
M* listCreat();//初始化
void listOut();//打印
M* listAdd();//增
M* listDel(); //删
void listSear();//查
M* listAdj();//改
int main() {
printf("%s\n", "链表长度:");
int Len;
scanf_s("%d",&Len);
M* List = listCreat(Len);
printf("\n%s\n", "打印List:");
listOut(List);
printf("\n%s\n", "插入位置:");
int Index;
scanf_s("%d", &Index);
List=listAdd(List,Index);
printf("\n%s\n", "打印List:");
listOut(List);
printf("\n%s\n", "删除位置:");
int Del;
scanf_s("%d", &Del);
List=listDel(List,Del);
printf("\n%s\n", "打印List:");
listOut(List);
printf("\n%s\n", "查找位置:");
int Search;
scanf_s("%d", &Search);
listSear(List,Search);
printf("\n%s\n", "打印List:");
listOut(List);
printf("\n%s\n", "更改位置:");
int Adjust,val;
scanf_s("%d", &Adjust);
printf("\n%s\n", "val:");
scanf_s("%d", &val);
List = listAdj(List, Adjust, val);
printf("\n%s\n", "打印List:");
listOut(List);
return 0;
}
M* listCreat(int step) {//初始化
M* head = NULL, * last = NULL, * p = NULL;
int steps = 0;
do {
M* p = (M*)malloc(sizeof(M));//申请储存空间
p->next = NULL;
printf("输入val:");
scanf_s("%d", &(p->val));
if (!head) {
head = p;
}
else {
last->next = p;
}
last = p;//令 last 指向 head 末尾
steps++;
} while (steps < step);
return head;
}
void listOut(M* head) {//输出链表
while (head != NULL) {
printf("val:%d\n", head->val);
head = head->next;
}
}
M* listAdd(M* head, int Index) {
M* p = (M*)malloc(sizeof(M));//申请储存空间
p->next = NULL;
printf("输入val:");
scanf_s("%d", &(p->val));
if (Index == 0) {
p->next = head;
head = p;
}
else {
M* In = head;
while (Index - 1 > 0) {
Index--;
In = In->next;
}
p->next = In->next;
In->next = p;
}
return head;
}
M* listDel(M* head, int Index) {
if (Index == 0) {
head = head->next;
}
else {
M* In = head;
while (Index - 1 > 0) {
Index--;
In = In->next;
}
In->next = In->next->next;
}
return head;
}
void listSear(M* head, int Index) {
M* p = head;
while (Index > 0) {
Index--;
p = p->next;
}
printf("val:%d\n", p->val);
}
M* listAdj(M* head, int Index, int data) {
M* p = head;
while (Index > 0) {
Index--;
p = p->next;
}
p->val = data;
return head;
}
链表基本功能:初始化、增、删、查、改
最新推荐文章于 2024-09-05 09:57:04 发布