题目描述
建立一个升序链表并遍历输出。
输入描述
输入的每个案例中第一行包括1个整数:n(1<=n<=1000),接下来的一行包括n个整数。
输出描述
可能有多组测试数据,对于每组数据,
将n个整数建立升序链表,之后遍历链表并输出。
示例
输入
4
3 5 7 9
输出
3 5 7 9
提示!
先排序,后建表。尾插法是关键。
Code
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Node {
public:
int value;
Node* next=nullptr;
Node(int val)
{
value = val;
next = nullptr;
}
};
Node* creatList(vector<int> a)
{
//升序
sort(a.begin(), a.end());
//尾插法建树
Node* p = new Node(0);
Node* head = p->next;
Node* p1 = nullptr;
bool flag = true;
for (int i = 0; i < a.size(); i++)
{
p1 = new Node(a[i]);
p->next = p1;
if (flag)
{
head = p->next;
flag = false;
}
p = p1;
}
return head;
}
void putValue(Node* p)
{
while (p)
{
cout << p->value << " ";
p = p->next;
}
}
int main()
{
int n;
vector<int> a;
int temp;
while (cin >> n)
{
Node* p = nullptr;
a.clear();
for (int i = 0; i < n; i++)
{
cin >> temp;
a.push_back(temp);
}
p = creatList(a);
putValue(p);
}
return 0;
}