A - 数据结构实验之链表一:顺序建立链表
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
Hint
不得使用数组!
链表真的很难理解,上次训练去晚了没及时接上TT,参考了网上题解根据个人理解写了代码如下
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node*next;
};
int main()
{
int n;
scanf("%d",&n);
struct node *head,*q,*p;
head=(struct node*)malloc(sizeof(struct node));
head->next=NULL;
q=head;
//struct node *head=(struct node*)malloc(sizeof(struct node));
//struct node *tail=(struct node*)malloc(sizeof(struct node));
//head->next=NULL;
//tail=head;
while(n--)//建立链表;
{
p=(struct node*)malloc(sizeof(struct node));
scanf("%d",&p->data);
p->next=NULL;//开一个节点放入数据,指针定义为空;
q->next=p;//q是一个游动指针,指向最后一个的指针;
q=p;//每一次q向后移动一位;
}
q=head->next;
while(q!=NULL)
{
if(q->next!=NULL)
printf("%d ",q->data);
else printf("%d\n",q->data);
q=q->next;
}
return 0;
}