数据结构实验之链表一:顺序建立链表
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
输入N个整数,按照输入的顺序建立单链表存储,并遍历所建立的单链表,输出这些数据。
Input
第一行输入整数的个数N;
第二行依次输入每个整数。
Output
输出这组整数。
Sample Input
8 12 56 4 6 55 15 33 62
Sample Output
12 56 4 6 55 15 33 62
Hint
不得使用数组!
Sour
链表的建立是学习数据结构所必须的基础,有好多人朋友觉得链表比较难,其实是没有弄明白其中的实际,一旦明白了链表的本质,学起来也没有那么难并且挺有趣。本题是顺序建立链表,是学习链表的基础。链表的建立无非就是利用好头尾结点来进行新数据的储存,并且建立一个P结点作为游动指针来进行游动的储存数据。要时刻注意尾结点与游动结点P的关系,实在不理解的朋友可以静下心来慢慢的推导一遍链表建立起来的过程。这里给出两种语言的建立链表的过程(C++较C来说简单)
AC代码:
C++
#include<bits/stdc++.h>
using namespace std;
typedef struct node
{
int data;
struct node*next;
}tree[1100];
int main()
{
struct node*head,*tail,*p;
head=new tree;
head->next=NULL;
tail=head;
int n;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
p=new tree;
scanf("%d",&p->data);
p->next=NULL;
tail->next=p;
tail=p;
}
p=head->next;
while(p)
{
if(p->next==NULL)
{
printf("%d\n",p->data);
}
else
{
printf("%d ",p->data);
}
p=p->next;
}
return 0;
}
C:
#include<stdio.h>
#include<stdlib.h>//这个头文件不要忘了,我在写C的时候忘了这个头文件结果malloc函数没法识别,大家不要犯我这样的错误。
struct node
{
int data;
struct node*next;
}s[1100];
int main()
{
struct node*head,*tail,*p;
head=(struct node*)malloc(sizeof(struct node));
head->next=NULL;
tail=head;
int n;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
p=(struct node*)malloc(sizeof(struct node));
scanf("%d",&p->data);
p->next=NULL;
tail->next=p;
tail=p;
}
p=head->next;
while(p)
{
if(p->next==NULL)
{
printf("%d\n",p->data);
}
else
{
printf("%d ",p->data);
}
p=p->next;
}
return 0;
}