c语言实现对链表的增改删差
直接上干货
#include<stdio.h>
#include<stdlib.h>
typedef struct data {
int value;
struct data* next;
}Ldata, * A;
//创建链表A
A init(int len) {
int i;
A p, r, list;
r = 0;
list = (A)malloc(sizeof(Ldata));
list->next = NULL;
for (i = 0; i < len; i++) {
p = (A)malloc(sizeof(Ldata));
p->value = i + 1;
p->next = NULL;
if (!list->next) {
list->next = p; //赋值头节点
}
else {
r->next = p;
}
r = p; //移动r指针,指向下一个节点
}
return list;
}
void change(A l, int num, int e) {//把num处的数据改为e
A q;
int i = 1;
q = l->next;
while (i != num && q->next != NULL) {
q = q->next;
i++;
}
if (i == num) {
q->value = e;
}
}
void charu(A l, int num, int e) {//在num处插入e
A p, q, ele;
int i = 1;
ele = (A)malloc(sizeof(Ldata));
ele->value = e;
ele->next = NULL;
p = q = l->next;
if (num == 1) { //将元素添加到链表头
l->next = ele;
ele->next = q;
return;
}
while (i != num && q->next != NULL) {
p = q;
q = q->next;
i++;
}
if (i == num) {
p->next = ele;
ele->next = q;
}
else if (i < num) { //将元素添加到链表尾
q->next = ele;
}
}
void dele(A l, int num) {//删除num节点的空间
A p, q;
int i = 1;
p = q = l->next;
if (num == 1) {
l->next = q->next;//头指针指向第二个
}
else {
while (i != num && q->next != NULL) {//不是最后一个和倒数第一个节点
p = q;
q = q->next;
i++;
}
if (i == num) {
p->next = q->next;
}
}
}
void putsLink(A l) {
A q;
q = l->next;
while (q->next != NULL) {
printf("%d ", q->value);//遍历链表输出,直到结尾前一个元素停止输出
q = q->next;
}
printf("\n");
//printf("%d\n", q->value); //打印最后一个元素
}
int main() {
A l;
l = init(60);//1~7创建链表
putsLink(l);
charu(l, 33, 40);//5号节点插入9
putsLink(l);
dele(l, 44);//删除2号节点
putsLink(l);
change(l, 1, 96);//6号节点改成15
putsLink(l);
return 0;
}
根据程序中给出的数据可得如下结果
多组测试数据如下