您的位置:首页 > 其它

遍历链表(单链表的基本操作)

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
来源:牛客网

题目描述

建立一个升序链表并遍历输出。 
输入描述:
输入的每个案例中第一行包括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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: