如何创建单链表?

如题所述

#include<stdio.h>
#include<stdlib.h>
struct LNode//定义单链表结点
{
int data;//定一结点的数据域
struct LNode *next;//定义结点的指针域
};
struct LNode *creat();//creat(创建单链表)函数的调用声明
void print (struct LNode *head,char a);//print(打印单链表)函数的调用声明
void main ()//主函数
{
struct LNode *head;
head = creat();//调用creat函数,创建一个单链表,并将单链表的头指针地址存放在指针 head 中
}
struct LNode *creat()//定义指针函数 creat(地址)及创建一个单链表 ,其返回值是一个单链表的首地址
{
struct LNode *head,*p,*rear;//定义指针变量
int x;
char a;
head=(struct LNode *)malloc(sizeof(struct LNode));/*申请 struct list 类型字节长的存储空间,第一个括号中内
容表示将申请空间的首地址经过强制类型转换为struct list *型
并把转换后的首地址存储在指针head中;*/
rear=head;//用一个需要移动的指针 rear 来存放头结点的地址
puts("input name of the list :\n");
scanf("%c",&a);//输入的链表名称只能用一个字母表示 ;若用两个则应为 : scanf("%c%c",&a,&b);
puts("input the list end with '-1':\n");//输入单链表的元素以 -1 结束
scanf("%d",&x);
while(x+1)//输入的数据为非零数 判断为真,当等于 -1 时为假,则跳出循环
{
p=(struct LNode *)malloc(sizeof(struct LNode));//同上
p->data=x;//将输入的值取出一个值并存储在结点 p 的数据域中
rear->next=p;//将结点 p 的首地址存放在 p 的前驱结点的指针域中
rear=p;//rear指针后移到下一个结点首地址处
scanf("%d",&x);//继续从输入的值中取出另一个值
}
rear->next=NULL;//指针 rear 移至最后一个结点处,将此结点的指针域 制空(NULL)
puts("the list you input is :");
print(head->next,a);//调用 print 函数
return head->next;//函数结束时返回创建的单链表的头指针(此头指针指向的结点为输入的第一个数值所存放的结点)
}
void print (struct LNode *head,char a)/*定义一个 print 函数,及打印函数,将单链表head中元素输出,
a为要输出单链表的名称*/
{
struct LNode *p;//定义一个需要移动的指针 p
p=head;//将单链表的首地址赋予指针 p
printf("%c = ( ",a);
while( p )//p存放的是地址,当 p 指向链表最后一个结点时 p=p->next(=NULL)为空,while判断为假,跳出循环
{
printf("%d ",p->data);//输出 p 指针指向的结点的数据域中存放的数值
p=p->next;//p指针后移,指向下一个结点首地址
}
puts(")");
}

同上但不带备注:

#include<stdio.h>
#include<stdlib.h>
struct LNode
{
int data;
struct LNode *next;
};
struct LNode *creat();
void print (struct LNode *head,char a);
void main ()
{
struct LNode *head;
head = creat();
}
struct LNode *creat()
{
struct LNode *head,*p,*rear;
int x;
char a;
head=(struct LNode *)malloc(sizeof(struct LNode));
rear=head;
puts("input name of the list :\n");
scanf("%c",&a);
puts("input the list end with '-1':\n");
scanf("%d",&x);
while(x+1)
{
p=(struct LNode *)malloc(sizeof(struct LNode));
p->data=x;
rear->next=p;
rear=p;
scanf("%d",&x);
}
rear->next=NULL;
puts("the list you input is :");
print(head->next,a);
return head->next;
}
void print (struct LNode *head,char a)
{
struct LNode *p;
p=head;
printf("%c = ( ",a);
while( p )
{
printf("%d ",p->data);
p=p->next;
}
puts(")");
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-12-17
首先构造一个结构体
结构体中含有一个指向本结构体的指针
然后声明一个指向本结构体类型的指针head_ptr;
依次往下申请链接即可
相似回答