题目描述:
输入N个整数,按照输入的顺序建立单链表存储,并遍历所建立的单链表,输出这些数据。
输入格式:
第一行输入整数的个数N(1 <= N <= 100000)。
第二行依次输入每个整数。
输出格式:
输出这组整数。
样例"输入样例:
8
12 56 4 6 55 15 33 62
输出样例:
12 56 4 6 55 15 33 62
参考代码:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *creat(int n)
{
struct node *head,*tail,*p;
int i;
head=(struct node*)malloc(sizeof(struct node));
head->next=NULL;
tail=head;
for(i=0;i<n;i++)
{
p=(struct node*)malloc(sizeof(struct node));
scanf("%d",&p->data);
p->next=NULL;
tail->next=p;
tail=p;
}
return head;
}
void show(struct node *p)
{
while(p!=NULL)
{
if(p->next==NULL)printf("%d\n",p->data);
else printf("%d ",p->data);
p=p->next;
}
}
int main()
{
int n;
struct node *head;
scanf("%d",&n);
head=creat(n);
show(head->next);
return 0;
}
顺序建链表是一个结点逐个插入的过程,其与逆序建链表的每次从头结点之后插入不同,是在最后一个结点之后插入。
链表最后一个结点常被称为尾结点,为了更好地标记插入位置,设置一个专门的指针变量来保存尾结点地址,该指针变量被称为尾指针。需要注意的是,当链表顺序插入结点后,尾指针的值要随之修改,以指向新的尾指针。
基本思路:
(1)首先建立一个只包含头结点的空链表,此时头指针、尾指针均指向头结点。 需要执行的操作是:
head=(struct node *) malloc ( sizeof ( struct node ) );
head->next=NULL; tail=head;
(2)在空链表头结点之后插入第一个结点。 需要执行的操作是:
p=(struct node *) malloc ( sizeof ( struct node ) );
scanf(“%d”,&p->data);
p->next=NULL;
tail->next=p;//对第一个结点而言,等价于head->next=p; tail=p;
(3)按照同样的操作,可以在上面的链表的尾结点之后插入第二个结点。
p=(struct node *) malloc ( sizeof ( struct node ) );
scanf(“%d”,&p->data); p->next=NULL;
tail->next=p;
tail=p; 按照这样的方式还可以继续插入后面每一个结点,而且每个结点的插入要执行的操作是完全一样的。