链表需要增删改查等功能,因为栈只能先进先出,不能从中间删除,所以链表不能放在栈中.
也不能放在data数据段中,因为数据段中的数据是程序加载时已经确定好了的.程序没结束时不能释放.
所以链表只能放在堆内存中.....
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
//构建一个链表节点
struct node
{
int data; //有效数据
struct node *pNext; //指向下一个节点的指针
};
int main(void)
{
struct node *p = (struct node *)malloc(sizeof(struct node));
if (NULL == p)
{
printf("malloc error.\n");
return -1;
}
//清理申请到的p指向的堆内存.
bzero(p,sizeof(struct node));
//给节点添加数据
p->data = 1;
p->pNext = NULL;
printf("节点的内容为:%d\n", p->data);
return 0;
}
创建了一个节点并填充了数据,打印测试完毕!!
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
//构建一个链表节点的结构体
struct node
{
int data; //有效数据
struct node *pNext; //指向下一个节点的指针
};
//申请内存创建一个节点的构造函数
struct node * creat_node(int data)
{
struct node *p = (struct node *)malloc(sizeof(struct node));
if (NULL == p)
{
printf("malloc error.\n");
return NULL;
}
//清理申请到的p指向的堆内存.
bzero(p,sizeof(struct node));
//给节点添加数据
p->data = data;
p->pNext = NULL;
return p;
}
int main(void)
{
struct node *pHead = NULL;
pHead = creat_node(1); //创建第一个节点node1
pHead->pNext = creat_node(2); //创建第二个节点node2
pHead->pNext->pNext = creat_node(3); //创建第三个节点node3
printf("node1的值是:%d\n",pHead->data);
printf("node2的值是:%d\n",pHead->pNext->data);
printf("node3的值是:%d\n",pHead->pNext->pNext->data);
return 0;
}