昨天看了c语言最后的一个链表了解 ,一开始没咋看懂,后来看了好几遍差不多明白了,今天打开csdn看了一个链表,然后自己打的(源代码不是我的噢)很开心
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *next;
}*PNODE,NODE;
PNODE init();
void insert(PNODE head,int number);
void print(PNODE head);
void freeall(PNODE head);
int main()
{
PNODE head=init();//这个地方之前没见过这样初始化的函数调用,学到了
int i;
for(i=0;i<10;i++)
{
insert(head,i);
}
print(head);
freeall(head);
return 0;
}
PNODE init()
{
PNODE temp=(PNODE)malloc(sizeof(NODE));
temp->next=NULL;//头指针指向的下一个为空,
//即为初始化,而不是头指针为空,头指针本来没有作用域
return temp;
}
void insert(PNODE head,int number)
{
PNODE temp=(PNODE)malloc(sizeof(NODE));
temp->data=number;
temp->next=head->next;//这个地方一定是把temp这个指针放在前面,将头指针赋给它
head->next=temp;
}
void print(PNODE head)
{
PNODE temp=head->next;
while(temp!=NULL)
{
printf("%d->",temp->data);
temp=temp->next;
}
printf("NULL!\n");
}
void freeall(PNODE head)
{
PNODE p=head,temp;
while(p!=NULL)//一定要标注p!=NULL
{
temp=temp->next;//这个地方写成p->next也行
free(p);
p=temp;
}
}