C语言构建动态链表并排序后输出(结构体)东大1521

东北大学在线编程社区problem1521
题目描述:创建包含二维点信息的动态链表,其成员数据为整型(x,y)坐标信息,从键盘输入多个点坐标,对这些点按其与原点的距离进行排序,输出其从小到大的排序结果。输入0时终止,输出格式"(%d,%d)\n"。
输入样例:
2 3
4 3
3 6
2 7
4 1
5 5
0 0
输出样例:
(2,3)
(4,1)
(4,3)
(3,6)
(5,5)
(2,7)

#include<stdio.h>
#include<stdlib.h>

struct point
{
	int x;
	int y;
	struct point* next;
};
typedef struct point PT;
PT* create()
{
	PT* head, * tail, * pnew;
	head = (PT*)malloc(sizeof(PT));
	int x, y;
	if (head == NULL)
		return 0;
	head->next = NULL;
	tail = head;
	while (1) {
		scanf("%d%d", &x, &y);
		if (x == 0 && y == 0)
			break;
		pnew = (PT*)malloc(sizeof(PT));
		pnew->x = x;
		pnew->y = y;
		pnew->next = NULL;
		tail->next = pnew;
		tail = pnew;
	}
	return head;
}
void sort(PT* head)
{
	PT* now, * tail;
	int a, b;
	int m, n;
	now = head->next;
	tail = NULL;
	if (now == NULL || now->next == NULL)
		return;
	while (now != tail&&now->next->x!=0) {
		while (now->next != tail) {
			a = (now->x * now->x) + (now->y * now->y);
			b = (now->next->x * now->next->x) + (now->next->y * now->next->y);
			if (a > b) {
				m = now->x;
				now->x = now->next->x;
				now->next->x = m;
				n = now->y;
				now->y = now->next->y;
				now->next->y = n;
			}
			now = now->next;
		}
		tail = now;
		now = head->next;
	}
}
void output(PT *head)
{
	PT* p;
	for (p = head->next; p != NULL; p = p->next) {
		printf("(%d,%d)\n", p->x, p->y);
	}
}
int main(void)
{
	PT* head, * pnew;
	head = create();
	putchar('\n');
	sort(head);
	output(head);
	return 0;
}

该代码在我的VS2019上运行出来的结果是正确的
在这里插入图片描述

但是我提交到OJ平台上显示“时间超限”,我想也许是在sort函数中使用的while语句中出现了死循环
在这里插入图片描述

但是个人能力有限,Debug不出什么名堂,也想不出更好的方法,所以烦请各位看官点评指教

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Patrick_Zhu_NEUer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值