遍历链表(单链表的基本操作)
2017-02-24 19:43
239 查看
链接:https://www.nowcoder.com/practice/7d348aa8b7d24e01a4f10bd023e2fb54?tpId=40&tqId=21548&tPage=11&rp=11&ru=/ta/kaoyan&qru=/ta/kaoyan/question-ranking
来源:牛客网
输入描述:
输出描述:
输入例子:
输出例子:
AC code:
#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<map>
#include<math.h>
#include<string.h>
#include<queue>
#include<vector>
#include<set>
#define LL long long
#define exp 1e-9
#define MAXN 1000010
using namespace std;
typedef struct LNode{
int data;
LNode *next;
}LNode;
int main()
{
// freopen("D:\\in.txt","r",stdin);
int i,n;
while(scanf("%d",&n)!=EOF)
{
LNode *head,*p,*pre,*newNode;
head = (LNode *)malloc(sizeof(LNode));
head->next=NULL;
for(i=1;i<=n;i++)
{
newNode = (LNode *)malloc(sizeof(newNode));
scanf("%d",&newNode->data);
p=head->next;
pre=head;
while(p)
{
if(p->data>newNode->data)
{
break;
}
else
{
pre=p;
p=p->next;
}
}
newNode->next=p;
pre->next=newNode;
}
p=head->next;
printf("%d",p->data);
p=p->next;
while(p)
{
printf(" %d",p->data);
p=p->next;
}
puts("");
}
return 0;
}
来源:牛客网
题目描述
建立一个升序链表并遍历输出。输入描述:
输入的每个案例中第一行包括1个整数:n(1<=n<=1000),接下来的一行包括n个整数。
输出描述:
可能有多组测试数据,对于每组数据, 将n个整数建立升序链表,之后遍历链表并输出。
输入例子:
4 3 5 7 9
输出例子:
3 5 7 9
AC code:
#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<map>
#include<math.h>
#include<string.h>
#include<queue>
#include<vector>
#include<set>
#define LL long long
#define exp 1e-9
#define MAXN 1000010
using namespace std;
typedef struct LNode{
int data;
LNode *next;
}LNode;
int main()
{
// freopen("D:\\in.txt","r",stdin);
int i,n;
while(scanf("%d",&n)!=EOF)
{
LNode *head,*p,*pre,*newNode;
head = (LNode *)malloc(sizeof(LNode));
head->next=NULL;
for(i=1;i<=n;i++)
{
newNode = (LNode *)malloc(sizeof(newNode));
scanf("%d",&newNode->data);
p=head->next;
pre=head;
while(p)
{
if(p->data>newNode->data)
{
break;
}
else
{
pre=p;
p=p->next;
}
}
newNode->next=p;
pre->next=newNode;
}
p=head->next;
printf("%d",p->data);
p=p->next;
while(p)
{
printf(" %d",p->data);
p=p->next;
}
puts("");
}
return 0;
}
相关文章推荐
- (2)单链表的操作 ① 输入一组整型元素序列,使用尾插法建立一个带有头结点的单链表。 ② 实现该线性表的遍历。 ③ 在该单链表的第i个元素前插入一个整数。 ④ 删除该单链表中的第i个元素,其值通过参数
- 数据结构学习笔记(二) 链表之单链表的基本操作
- 数据结构之单链表、双链表的基本操作
- 单链表的基本操作(创建、删除、插入、遍历)
- 数据结构(第二天)单链表的基本操作,创建单链表,头插法,尾插法,删除节点,查询节点
- 单链表的基本操作(初始化,建表,遍历,增加,删除,查找,逆序)等操作
- 单链表、双链表的基本操作
- Java单链表基本操作(四)--单链表反转
- 单链表和双链表上的基本操作
- 数据结构之链表(1):单链表基本操作
- 单链表的基本操作(建立.遍历.添加.删除)
- 单链表的基本操作-数据结构
- 单链表的基本操作
- 用java简单的实现单链表的基本操作
- 单链表的一些基本操作
- 链表-基本操作(C版)
- 单链表的基本操作实现
- C链表基本操作 笔试常考类型
- 单链表的基本操作
- 7.4 7.5 二叉树的基本操作与遍历