东北大学在线编程社区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不出什么名堂,也想不出更好的方法,所以烦请各位看官点评指教