PAT 甲级 1052 Linked List Sorting (25分) 哈希表 排序

原题链接1052 Linked List Sorting (25分)

分析:

使用哈希map对数据进行读入,将在这条链表上的放到vector中。
注意for循环在链表中的应用。

满分代码:

#include <iostream>
#include <vector>
#include <set>
#include <map>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <unordered_map>
#define inf 0x3f3f3f3f
typedef long long LL;
using namespace std;
const int MAXN = 1e3+10;
/*
	神奇的for循环遍历 
	1. 写结构体的时候注意输入和放入顺序 
*/
struct Node {
	string address;
	int key;
	string next;
	
	bool operator< (const Node& t) {
		return key < t.key;
	}
};

int main() {
	int n;
	char head[10];
	scanf("%d %s", &n, head);
	// address Node
	unordered_map<string, Node> map;
	char address[10], next[10];
	for(int i = 0; i < n; i++) {
		int key;
		scanf("%s%d%s", address, &key, next);
		map[address] = {address, key, next};
//		auto & p = map[address];	// 读入检验 
//		cout << p.address << " " << p.key << " " << p.next << endl;
	}
	vector<Node> nodes;
	for(string i = head; i != "-1"; i = map[i].next) {
		nodes.push_back(map[i]);
	}
	printf("%d ", nodes.size());
	if(nodes.empty()) {
		puts("-1");
	} else {
		sort(nodes.begin(), nodes.end());
		printf("%s\n", nodes[0].address.c_str());
		for(int i = 0; i < nodes.size(); i++) {
			if(i == nodes.size() - 1) {
				printf("%s %d -1\n", nodes[i].address.c_str(), nodes[i].key);
			} else {
				printf("%s %d %s\n", nodes[i].address.c_str(), nodes[i].key, nodes[i+1].address.c_str());
			}
		}
	}
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值