数据结构实验之链表一:顺序建立链表(C和C++)

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

Time Limit: 1000 ms Memory Limit: 65536 KiB

Submit Statistic

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; 
}

 

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值