您的位置:首页 > 理论基础 > 数据结构算法

数据结构实验之链表一:顺序建立链表(构造函数)

2016-09-29 14:14 405 查看


数据结构实验之链表一:顺序建立链表

Time Limit: 1000MS Memory Limit: 65536KB


Problem Description

输入N个整数,按照输入的顺序建立单链表存储,并遍历所建立的单链表,输出这些数据。


Input

第一行输入整数的个数N;

第二行依次输入每个整数。


Output

输出这组整数。


Example Input

8
12 56 4 6 55 15 33 62



Example Output

12 56 4 6 55 15 33 62




Code realization

#include <stdio.h>
#include <stdlib.h>
typedef struct LNode
{
int data;
struct LNode *next;
}LNode;
//输入函数
LNode *input(int n)
{
LNode *head, *tail, *p;
head = (LNode*)malloc(sizeof(LNode));
tail = head;
for(int i=0;i<n;i++)
{
p = (LNode*)malloc(sizeof(LNode));
scanf("%d",&p->data);
tail->next = p;
tail = p;
tail->next = NULL;
}
return head;
}
void output(LNode *head)
{
LNode *p;
p = head->next;
while(p)
{
printf("%d",p->data);
p = p->next;
if(p)
printf(" ");
else
printf("\n");
}
}
int main()
{
LNode *head;
int n;
scanf("%d",&n);
head = input(n);
output(head);
return 0;
}
(方法二)
#include <stdio.h>
#include <stdlib.h>
typedef struct LNode
{
int data;
struct LNode *next;
}LNode;
//输入函数
void input(LNode *head, LNode *tail, int n)
{
LNode  *p;
for(int i=0;i<n;i++)
{
p = (LNode*)malloc(sizeof(LNode));
scanf("%d",&p->data);
tail->next = p;
tail = p;
tail->next = NULL;
}
}
void output(LNode *head)
{
LNode *p;
p = head->next;
while(p)
{
printf("%d",p->data);
p = p->next;
if(p)
printf(" ");
else
printf("\n");
}
}
int main()
{
LNode *head,*tail;
int n;
scanf("%d",&n);
head = (LNode*)malloc(sizeof(LNode));
tail = head;
input(head,tail,n);
output(head);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息