遍历链表

题目描述

建立一个升序链表并遍历输出。

输入描述:

输入的每个案例中第一行包括1个整数:n(1<=n<=1000),接下来的一行包括n个整数。

输出描述:

可能有多组测试数据,对于每组数据,
将n个整数建立升序链表,之后遍历链表并输出。

示例1

输入

复制

4
3 5 7 9

输出

复制

3 5 7 9

使用堆排序排序后,构造链表,再遍历输出

#include<iostream>
#include<algorithm>
using namespace std;
struct ListNode
{
	int val;
	struct ListNode* next;
	ListNode(int n) :val(n), next(nullptr)
	{
	}
};
void sink(int a[], int b, int c)
{
	int p = b;
	while (p <= c / 2)
	{
		int tmp = -1;
		if (a[p] > a[p * 2])
			tmp = p;
		else
			tmp = p * 2;
		if (p * 2 + 1 <= c)
		{
			if (a[tmp] < a[p * 2 + 1])
				tmp = p * 2 + 1;
		}
		if (tmp == p)
			break;
		swap(a[tmp], a[p]);
		p = tmp;
	}
}
void heapsort(int a[], int x, int y)
{
	for (int i = y / 2; i >= x; i--)
	{
		sink(a, i, y);//从一半的时候开始调整,只有这样的节点才有叶节点,调整堆的函数。 
	}
	int t = 0;
	while (t + 1 < y)
	{
		swap(a[x], a[y - t + x - 1]);
		t++;
		sink(a, x, y - t + x - 1);
	}
}

int main()
{
	int n;

	while (cin >> n)
	{
		int a[1005];
		for (int i = 1; i <= n; i++)
		{
			cin >> a[i];
		}
		heapsort(a, 1, n);
		ListNode *head = nullptr;
		ListNode *p = new ListNode(a[1]);
		head = p;
		for (int i = 2; i <= n; i++)
		{
			ListNode *tmp = new ListNode(a[i]);
			p->next = tmp;
			p = p->next;
		}
		while (head != nullptr)
		{
			ListNode *t = head;
			cout << head->val << " ";
			head = head->next;
			delete t;
		}
		cout << endl;
	}

	return 0;
}

猜你喜欢

转载自blog.csdn.net/cx1165597739/article/details/90173039