1052. Linked List Sorting

本文介绍了一种基于链表的排序算法实现过程。通过在内存中处理散列节点,将其组织成一个或多个有序链表。文章详细展示了如何使用二分查找等数据结构操作来高效完成任务,并提供了完整的C++代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

没仔细审题,走了很多弯路。题目要求:内存中有很多散列的节点,可能构成不止一个链表。其次要注意空链表的情况。

// 1052. Linked List Sorting.cpp: 主项目文件。

#include "stdafx.h"
#include <cstdio>
#include <algorithm>
using namespace std;

const int N=100003;
typedef struct Node{
	int add,data,next;
}Node;
Node node[N],list[N];
int n;

bool cmp1(Node m1,Node m2){
	return m1.add<m2.add;
}

bool cmp(Node m1,Node m2){
	return m1.data<m2.data;
}

int binarySearch(int vAdd,int low,int high){
	if(low<=high){
		int mid=low+(high-mid)>>1;
		if(vAdd==node[mid].add)
			return mid;
		else if(vAdd<node[mid].add)
			return binarySearch(vAdd,low,mid-1);
		else
			return binarySearch(vAdd,mid+1,high);
	}
	return -1;
}

int creatList(int head){
	int curAdd=head,cnt=0;
	while(curAdd!=-1){
		list[cnt].add=curAdd;
		int index=binarySearch(curAdd,0,n-1);
		list[cnt].data=node[index].data;
		list[cnt++].next=node[index].next;
		curAdd=node[index].next;
	}
	return cnt;
}

int main()
{
	int head;
    scanf("%d%d",&n,&head);
	for(int i=0;i<n;i++)
		scanf("%d%d%d",&node[i].add,&node[i].data,&node[i].next);
	sort(node,node+n,cmp1);
	int listLength=creatList(head);
	sort(list,list+listLength,cmp);
	if(listLength==0){
		printf("0 -1\n");
		return 0;
	}
	printf("%d %05d\n",listLength,list[0].add);
	for(int i=0;i<listLength-1;i++){
		printf("%05d %d %05d\n",list[i].add,list[i].data,list[i+1].add);
	}
	printf("%05d %d -1\n",list[listLength-1].add,list[listLength-1].data);
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值