参考博文:http://data.biancheng.net/view/161.html
对链表中数据元素做"增删查改"的操作实例代码如下:
#include <stdio.h>
#include <stdlib.h>
typedef struct Link {
int elem;
struct Link *next;
} link;
link *initLink();
//链表插入的函数,p是链表,elem是插入的结点的数据域,add是插入的位置
link *insertElem(link * p, int elem, int add);
//删除结点的函数,p代表操作链表,add代表删除节点的位置
link *delElem(link * p, int add);
//查找结点的函数,elem为目标结点的数据域的值
int selectElem(link * p, int elem);
//更新结点的函数,newElem为新的数据域的值
link *amendElem(link * p, int add, int newElem);
void display(link *p);
int main(void)
{
link *p = NULL;
int address;
//初始化链表(1,2,3,4)
printf("初始化链表为:\n");
p = initLink();
display(p);
printf("\n在第4个节点的位置插入数据5:\n");
p = insertElem(p, 5, 4);
display(p);
printf("\n删除第3个节点:\n");
p = delElem(p, 3);
display(p);
printf("\n查找数据是2的节点为:\n");
address = selectElem(p, 2);
if (address == -1) {
printf("\n没有该节点");
} else {
printf("\n数据是2的节点为:%d\n", address);
}
printf("\n更改第3个节点的位置上的数据为7:\n");
p = amendElem(p, 3, 7);
display(p);
return 0;
}
link *initLink()
{
link *p = (link*)malloc(sizeof(link));//创建一个头结点【】
link *temp = p;//声明一个指针指向头结点,用于遍历链表;(中间变量temp节点:始终指向链表的最后1个节点)
int i = 0;
//生成链表
for (i = 1; i < 5; i++) {
/// 创建新节点,并初始化
link *a = (link*)malloc(sizeof(link));
a->elem = i * 2;
a->next = NULL;
/// 将新节点插入链表末尾
temp->next = a;
temp = temp->next;
}
return p;
}
link *insertElem(link *p, int elem, int add)
{
link *temp = p;//创建临时结点temp
link *c = NULL;
int i = 0;
//首先找到要插入位置的上一个结点
for (i = 1; i < add; i++) {
if (temp == NULL) {
printf("插入位置无效\n");
return p;
}
temp = temp->next;
}
//创建插入结点c
c = (link*)malloc(sizeof(link));
c->elem = elem;
//向链表中插入结点
c->next = temp->next;
temp->next = c;
return p;
}
link *delElem(link * p, int add)
{
link * temp = p;
link * del = NULL;
int i = 0;
//遍历到被删除结点的上一个结点
for (i = 1; i < add; i++) {
temp = temp->next;
}
del = temp->next;//单独设置一个指针指向被删除结点,以防丢失
temp->next = temp->next->next;//删除某个结点的方法就是更改前一个结点的指针域
free(del);//手动释放该结点,防止内存泄漏
return p;
}
int selectElem(link * p, int elem)
{
link * t = p;
int i = 1;
while (t->next) {
t = t->next;
if (t->elem == elem) {
return i;
}
i++;
}
return -1;
}
link *amendElem(link * p, int add, int newElem)
{
int i = 0;
link * temp = p;
temp = temp->next;//tamp指向首元结点
//temp指向被删除结点
for (i = 1; i < add; i++) {
temp = temp->next;
}
temp->elem = newElem;
return p;
}
void display(link *p)
{
link* temp = p;//将temp指针重新指向头结点
//只要temp指针指向的结点的next不是Null,就执行输出语句。
while (temp->next != NULL) {
temp = temp->next;
printf("%d ", temp->elem);
}
printf("\n");
}