实现链表的增删查改
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
struct Linklist
{
int data;
struct Node * Pnext;
};
typedef struct Linklist Node;
//增 尾部插入节点
Node * addback(Node * phead,int insertdata)
{
Node * newnode = malloc(sizeof(Node)); //新建节点
newnode->data = insertdata;
newnode->Pnext = NULL;
if (phead == NULL)
{
phead= newnode;
}
else
{
Node * temp = phead; //备份头结点
while (temp->Pnext !=NULL)
{
temp = temp->Pnext; //不断循环
}
temp->Pnext = newnode;
}
return phead;
}
//删 删除节点
Node * deleteNode(Node *phead, int deleteData)
{
if (phead == NULL)
{
return ;
}
Node * pre =NULL;
Node * cur =phead;
int flag = 0; //0表示没找到 1 表示找到
while (cur!=NULL)
{
if (cur->data == deleteData)
{
flag = 1;
break;
}
pre = cur;
cur =cur->Pnext;
}
if (flag == 0) //如果没找到
{
printf("不存在要删除的数");
}
else //如果找到
{
if (cur == phead) //如果要删除的是第一个节点
{
phead = phead->Pnext;
free(cur);
}
else
{
pre->Pnext = cur->Pnext; //删除的节点不是第一个节点
free(cur);
}
}
return phead;
}
//查询
Node * findData(Node * phead, int findData)
{
int flag = 0;
while (phead != NULL) //遍历链表
{
if (phead->data == findData)
{
flag = 1;
printf("find %d \n", findData);
break;
}
phead = phead->Pnext;
}
if (flag == 1)
{
return phead; //返回找到数据的节点的指针
}
else
{
printf("\n not find ");
return NULL; //没找到
}
}
// 改 改变节点数据
Node * changeData(Node * phead, int findData, int changeData)
{
int flag = 0;
while (phead != NULL) //遍历链表
{
if (phead->data == findData)
{
flag = 1;
break;
}
phead = phead->Pnext;
}
if (flag == 1)
{
phead->data = changeData;
return phead; //返回找到数据的节点的指针
}
else
{
return NULL; //没找到
}
}
//打印链表
void showlist(Node *phead)
{
while (phead != NULL)
{
printf("\n %d", phead->data);
phead = phead->Pnext;
}
}
void main()
{
Node * phead = NULL;
phead = addback(phead, 1);
phead = addback(phead, 2);
phead = addback(phead, 3);
phead = addback(phead, 4);
phead = addback(phead, 5);
phead = deleteNode(phead, 1);
changeData(phead,5, 16);
showlist(phead);
findData(phead, 4);
system("pause");
}