#include<stdio.h>
#include<stdlib.h>
struct Node
{
int date;
struct Node next;
};
struct Node cendhead()
{
struct Node headnode = (struct Node )malloc(sizeof(struct Node));
headnode->next = NULL;
return headnode;
};
struct Node cendnode(int date)
{//创建节点的函数,把别人的数据变成节点的磨样
struct Node newnode = (struct Node)malloc(sizeof(struct Node)); //申请内存不对,导致释放问题
newnode->date = date;
newnode->next = NULL;
return newnode;
};
void inserthead(struct Nodeheadnode,int date)
{//表头插入
struct Nodenewnode = cendnode(date);
newnode->next = headnode->next;
headnode->next = newnode;
}
//函数封装打印
void printlist(struct Nodeheadnode)
{
struct Node pmove = headnode->next;
while (pmove!=NULL)
{
printf("%d\t", pmove->date);
pmove = pmove->next;
}
printf("\n");
}
//查找节点
struct Nodesearchdate(struct Nodeheadnode, int date)
{
struct Nodepmove = headnode->next;
while (pmove!=NULL&&pmove->date!=date)
{
pmove = pmove->next;//以此循环
}
return pmove;
}
//删除节点 需要两个节点,找指定位置,和指定位置的左边的节点
void deletenode(struct Node headenode,int psodate )
{
struct Node psonodeleft = headenode;//左边的作为头
struct Node* psonode = headenode->next;//右边的赋值给下一个节点
while (psonode != NULL&&psonode->date!= psodate)
{
psonodeleft = psonode;
psonode = psonode->next;
}
if (psonode == NULL)
{
printf(“未找到该位置,无法删除”);
return;
}
else
{
psonodeleft->next = psonode->next;
//左边节点的指针,指向右边节点的指针
free(psonode);
psonode = NULL;
printf(“删除成功!\n”);
}
}
//删除所有相同的数据
void deleteall(struct Node* headnode, int date)
{
while (searchdate(headnode, date) != NULL);//查找是否又要删除的数据
{
deletenode(headnode, date);//进行删除
}
}
//插入节点 先找到表尾,然后进行插入
void insernode(struct Node* headnode, int date)
{
struct Nodenewnode = cendnode(date);
struct Nodetailnode = headnode;
}
int main()
{ //有头链表:莫一种结构的单一个体
struct Node* list = cendhead();
for (int i = 0; i < 3; i++)
{
inserthead(list,i);
}
printlist(list);
deletenode(list, 1);
printlist(list);
return 0;
}