有头链表的创建 插入 删除
struct Node
{
int date;
struct Nodenext;
};
struct Node cendnode(int date)
{//创建链表
struct Nodenewnode = (struct Node)malloc(sizeof(struct Node));
newnode->date = date;
newnode->next = NULL;
return newnode;
}
struct List
{
struct Node* firnode;//永远指向表头
struct Node* tailnode;//永远指向表尾
int listsize;
};
struct Listcentlist()
{
struct Listlist = (struct List*)malloc(sizeof(struct List*));
list->listsize = 0;
list->firnode = NULL;
list->tailnode = NULL;
return list;
}
void inserthead(struct List*list ,int date )//尾插法插入
{
struct Node * newnode = cendnode(date);
if (list->listsize == 0)
{
list->firnode = newnode;
list->tailnode = newnode;
}
else
{
newnode->next = list->firnode;
list->firnode = newnode;
}
list->listsize++;
}
void detelhead(struct Listlist)//删除链表
{
if (list->listsize != 0)//判断链表里面是否存在数值
{
struct Node nextnode = list->firnode->next;
free(list->firnode);
list->firnode = nextnode;//把表头指向新的节点
}
}
void printlist(struct Listlist)//打印链表
{
struct Nodepmove = list->firnode;
while (pmove!=NULL)
{
printf("%d\t", pmove->date);
pmove = pmove->next;
}
printf("\n");
}
int main()
{//无头链表:一般采用在封装的方式
struct List*list = centlist();
for (int i = 0; i < 3; i++)
{
inserthead(list, i);
}
detelhead(list);
detelhead(list);
inserthead(list, 3);
printlist(list);
}
理解思路: