- 论坛徽章:
- 0
|
新手勿喷,今天学习到动态链表相关知识,根据文档学习后自己编了个小程序,但是为什么p2-next = NULL,得不到正确的结果,反而是p2 = NULL能得到正确结果,详见红字部分代码。
- /***********************************
- **程序:test_node_1(线性链表测试)
- **作者:lwp
- **日期:20140506
- **版本:v1.0
- **功能:创建一个存放3组数据的动态链表
- **
- ***********************************/
- #include <stdio.h>
- #include <string.h>
- #define LEN sizeof(struct student)
- typedef struct student{
- char name[10];
- int age;
- struct student *next;
- };
- struct student *creat();
- int main(int argc,char* argv[])
- {
- struct student *p;
- p = creat();
- do
- {
- printf("name->%s,age->%d\n",p->name,p->age);
- p = p->next;
- }while(p != NULL);
- return 0;
- }
- struct student *creat(void)
- {
- struct student *head,*p1,*p2;
- p1=p2=(struct student*)malloc(LEN);
- scanf("%s%d",&p1->name,&p1->age);
- head = NULL;//线性链表头指向一个空结点
- head = p1; //头指针head指向p1分配的首结点
- while(1)
- {
- p1 = (struct student*)malloc(LEN); //p1继续开辟新结点
- scanf("%s%d",&p1->name,&p1->age);
- if(p1->age == 0) break;
- p2->next = p1; //p1开辟的新节点链接到p2结点后面
- p2 = p1;
- }
- printf("p2->name=%s,p2->age=%d\n",p2->name,p2->age);
- [color=Red]p2->next = NULL;[/color]
- free(p1);
- free(p2);
- return(head); //返回链表头指针
- }
复制代码 |
|