1.定义结构体
#include
//定义结构体
struct node{
int data;
struct node* next;
};
2.创建链表
struct node* creatlist()
{
struct node* headnode = (struct node*)malloc(sizeof(struct node));
//headnode 成为了结构体变量
//变量使用前必须被初始化
//headnode->data =1;
headnode->next =NULL;
return headnode;
}
3.创建结点(结构体变量)
struct node* createnode(int data)
{
struct node* newnode = (struct node*)malloc(sizeof(struct node));
newnode->data = data;
newnode->next = NULL;
return newnode;
}
4.打印结点
void printlist(struct node* headnode)
{
struct node* pr = headnode->next;
while(pr->next!=NULL)
{
printf("%d",pr);
pr = pr->next;
}
printf("\n");
}
5.插入结点、参数;插入那个链表,插入的结点的数据是多少
void insertnodebyhead(struct node* headnode,int data)
{
struct node* newnode = createnode(data); //通过调用子函数,创建结点
newnode->next = headnode->next; //头插法,headnode->next为下一个结点(表头下一个结点)的地址,newnode的指针域指向下一个结点(地址)
headnode->next = newnode; // 原表头指向新建的结点(地址)
}
6.主函数main
int main()
{
struct node* list = createlist();
insertnodebyhead(list,1);
insertnodebyhead(list,2);
insertnodebyhead(list,3);
printlist(list);
system("pasue");
return 0;
}