我们对链表有了一个初步的认识之后,就要开始学习对链表的一些基本操作,例如对链表的数据的添加,删除,查找和更改
带头节点的链表的创建(头插法和尾插法)
typedef struct Link{
int data;
struct Link *next;
} link;
//头插法
link *create1(){
link *head = (link *)malloc(sizeof(link));
head -> next = NULL;
link *pnew = NULL;
head -> next = pnew;
int count;
printf("请输入链表的长度\n");
scanf("%d", &count);
for(int i = 0; i < count; i++){
pnew = (link *)malloc(sizeof(link));
scanf("%d",&pnew -> data);
pnew -> next = head -> next;
head -> next = pnew;
}
return head;
}
//尾插法
link *create2(){
link *head = (link *)malloc(sizeof(link));
head -> next = NULL;
link *end = NULL;
end = head;
int count;
printf("请输入链表的长度\n");
scanf("%d", &count);
for(int i = 0; i< count; i++){
link *node = (link *)malloc(sizeof(link));
scanf("%d",&node -> data);
end -> next = node;
end = node;
}
end -> next = NULL;
return head;
}
链表的输出
void print(link *head){
link *node = head;
while(node -> next != NULL){
node = node -> next;
printf("%d",node -> data);
}
}
数据的插入
同顺序表一样,向链表中增添元素,根据添加位置不同,可分为以下 3 种情况:
- 插入到链表的头部(头节点之后),作为首元节点;
- 插入到链表中间的某个位置;
- 插入到链表的最末端,作为链表中最后一个数据元素;
其中最重要的就两步:将新结点的 next 指针指向插入位置后的结点;
将插入位置前结点的 next 指针指向插入结点;
link *insert(link *head){
link *tem = head;
int m, n;
printf("请输入要插入的位置和数值:\n");
scanf("%d %d", &m, &n);
for(int i = 0; i< m; i++){
tem = tem -> next;
}
link *pnew = (link *)malloc(sizeof(link));
pnew -> data = n;
pnew -> next = tem -> next;
tem -> next = pnew;
return head;
}
数据的删除
删除节点的实质就是将不用的节点摘除,并释放掉该节点的内存空间
核心代码为:
temp->next=temp->next->next;
- 第一种是通过位置查找并删除
//不能遍历到该节点,必须遍历到上一个节点。
link *del1(link *head){
link *tem = head;
int count;
printf("请输入删除节点的位置:\n");
scanf("%d",&count);
for(int i = 1; i < count; i++){//遍历到上一个节点
tem = tem -> next;
if(tem -> next == NULL){
printf("没有该节点!\n");
return head;
}
}
link *del = (link *)malloc(sizeof(link));
del = tem -> next;
tem -> next = tem -> next -> next;
free(del);//手动释放该节点
return head;
}
- 第二种是通过指定数据来删除
link *del2(link *head){
link *tem = head;
int num;
printf("请输入删除节点的值:\n");
scanf("%d", &num);
while(tem -> next -> data != num){
tem = tem -> next;
}
link *del = (link *)malloc(sizeof(link));
del = tem -> next;
tem -> next = tem -> next -> next;
free(del);//手动释放该节点
return head;
}
数据的查找
从表头依次遍历表中节点,用被查找元素与各节点数据域中存储的数据元素进行比对,直至比对成功或遍历至链表最末端的 NULL(比对失败的标志)。
int seek(link *head){
link *tem = head;
int i = 0, count;
printf("请输入需要查找的值:\n");
scanf("%d", &count);
while(tem -> next -> data != count){
tem = tem -> next;
i++;
if(tem -> next == NULL){
return -1;
}
}
return i + 1;
}
数据的更改
通过遍历找到该节点,然后直接修改其中的值即可
link *replace(link *head){
link *tem = head;
int m, n;
printf("请输入要修改的位置和数值:\n");
scanf("%d%d", &m, &n);
for(int i = 0; i < m; i++){
tem = tem -> next;
}
tem -> data = n;
return head;
}