求解链表中的p1,p2有什么作用。

qq_45017455 2019-05-23 09:19:10
#include<stdio.h> #include<stdlib.h> #include<conio.h> struct station { char name[8]; struct station *nextSta; }; strut station *creat_sta( station *h) void print_string(struct string *h); int num=0;//全局变量表示站点数 main() { struct station *head;//定义表头指针 head=NULL;//创建一个空表 printf("请输入站名:"); head=creat_sta(struct station *h)//调用函数创建链表 printf("--------------------------"); printf("共有%d个站点:\n,num"); print_sta(head); } struct station *creat_sta(struct station *h) { struct station *p1,*p2; p1=p2=(struct station*)malloc(sizeof(struct station));//申请新节点 if(p2!=NULL) { scanf("%s",&p2->name); p2->nextSta=NULL; } while(p2->name[0]!='#') { num++; if(h==NULL) h=p2; else p1->nextSta=p2; p1=p2; p2=(struct station*)malloc(sizeof(struct station)); if(p2!=NULL) { scanf("%s",&p2->name); p2->nextSta=NULL; } } return h; } void print_sta(struct station *h) { struct station *temp; temp=h; while(temp!=NULL) { printf("%-8s",temp->name); temp=temp->nextSta; } }
...全文
107 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
赵4老师 2019-05-23
  • 打赏
  • 举报
回复
数据结构对单链表进行数据排序 http://bbs.csdn.net/topics/392201633
棉猴 2019-05-23
  • 打赏
  • 举报
回复
p1是加入链表中的节点,p2是新创建的节点。
另外代码稍微修改了一下
// ConsoleApplication4.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
struct station
{
char name[8];
struct station *nextSta;
};
struct station *creat_sta(station *h);
void print_sta(struct station *h);
int num = 0;//全局变量表示站点数
int main()
{
struct station *head;//定义表头指针
head = NULL;//创建一个空表
printf("请输入站名:");
head = creat_sta(head);//调用函数创建链表 printf("--------------------------");
printf("共有%d个站点:\n",num);
print_sta(head);
}
struct station *creat_sta(struct station *h)
{
struct station *p1, *p2;
p1 = p2 = (struct station*)malloc(sizeof(struct station));//申请新节点
if (p2 != NULL)
{
scanf("%s", &p2->name);
p2->nextSta = NULL;
}
while (p2->name[0] != '#')
{
num++;
if (h == NULL)
h = p2;
else
p1->nextSta = p2;
p1 = p2;
p2 = (struct station*)malloc(sizeof(struct station));
if (p2 != NULL)
{
scanf("%s", &p2->name);
p2->nextSta = NULL;
}
}
return h;
}
void print_sta(struct station *h)
{
struct station *temp;
temp = h;
while (temp != NULL)
{
printf("%-8s", temp->name);
temp = temp->nextSta;
}
return ;
}

VS2015调试结果为

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧