数据结构实验之链表一:顺序建立链表
Description
输入N个整数,按照输入的顺序建立单链表存储,并遍历所建立的单链表,输出这些数据。
Input
第一行输入整数的个数N;
第二行依次输入每个整数。
Output
输出这组整数。
Sample
Input
8
12 56 4 6 55 15 33 62
Output
12 56 4 6 55 15 33 62
第一种:
#include <stdio.h>
#include <stdlib.h>
struct node//定义链表类型
{
int data;//数据域
struct node *next;//指针域
};
int main()
{
struct node *head,*p,*tail;//定义头指针、游动指针和尾指针
head=(struct node *)malloc(sizeof(struct node));
head->next=NULL;
tail=head;//建立只包含头结点的空链表,头指针、尾指针均指向头结点。初始化tail指向head,tail指针总是只想最后一个结点。
int n,i;
scanf("%d",&n);
for(i=1;i<=n;i++)//循环建立新结点p,并插入到尾结点tail的后面
{
p=(struct node *)malloc(sizeof(struct node));//为新结点分配存储空间
scanf("%d",&p->data);//读入数据,赋给新结点数据域
p->next=NULL;//让p的next等于空,让新结点指针域指向原来头结点后面的结点
tail->next=p;//让头结点next域指向新结点p
tail=p;
}
p=head->next;//让p指向第一个结点
while(p!=NULL)//当p为空时跳出循环
{
printf("%d ",p->data);
p=p->next;
}
return 0;
}
第二种:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
} s;//链表是把结点连接起来,首先建立链表的结点,里面存放数据域和指针域
struct node *creat(int n)
{
int i;
struct node *head,*p,*tail;
head=(struct node *)malloc(sizeof(struct node));
head->next=NULL;
tail=head;//申请一个头节点让它为空,让尾指针指向
for(i=1; i<=n; i++)
{
p=(struct node *)malloc(sizeof(struct node));
scanf("%d",&p->data);
p->next=NULL;//p现在是一个存放了数据和指针的结点
tail->next=p;//要把p连接在链表中就要把p连接在尾结点之后,要连接尾结点和p,如果想要把尾结点和p连接在一起,那就要把p的地址记下来,用tail记p的地址,就是tail->next=p,这样就把p的地址记下来了,
tail=p; //连接起新的链表之后,就需要把尾结点放在最后,tail=p
}
return head;
};
void print(struct node *head)
{
int n=0;
struct node *p;
p=head->next;
while(p)//只要p不为空
{
n++;
if(n==1)
printf("%d",p->data);
else
printf(" %d",p->data);//输出p所保存的数据,输出结束后指向下一个
p=p->next;
}
printf("\n");//n保证空格数量完全一致
}
int main()
{
int n;
scanf("%d",&n);
struct node *head;
head=creat(n);
print(head);
return 0;
}
注意:
在head=(struct node *)malloc(sizeof(struct node));中
sizeof(struct node)
//就是求 struct node 这个结构体占用的字节数。
malloc(sizeof(struct node))
//申请 struct node 这个结构体占用字节数大小的空间
(struct node *) malloc(sizeof(struct node))
//将申请的空间的地址强制转化为 struct node * 指针类型
head=(struct node *) malloc(sizeof(struct node))
//将那个强制转化的地址赋值给 head.