题目链接:http://pat.zju.edu.cn/contests/pat-a-practise/1052
这个题目告诉我们:读题、理解题目、分析题目很重要。
题目说只有1个链表了吗?
题目说链表的结尾一定是NULL了吗?
链表空的时候应该输出什么?
另外,都注意到NULL定义为-1了。
这个题目用hash的方法,很适合的。因此也可以试着用map。
数组hash的方法见:http://blog.csdn.net/sunbaigui/article/details/8656800。
给出2个代码,总体思路上是一样的,仅仅部分细节处理方式不同。
代码1
// 1. 题目没有说仅有1条链表
// 2. 所给的链表空时输出0 -1
// 3. 题目没有说结尾是null
#include
#include
#include
#include
代码2
#include <stdio.h>
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
#define MAXADDR 1000000
using namespace std;
struct Node
{
int add;
int value;
int next;
bool operator < (const Node& A) const
{
return value < A.value;
}
};
int N, head;
vector<Node> buf;
vector<Node> list;
map<int, int> m;
void Output()
{
int i;
for(i=0; i<buf.size() ; i++)
{
printf("%d %d %d\n", buf[i].add, buf[i].value, buf[i].next);
}
}
void Input()
{
scanf("%d %d", &N, &head);
Node temp;
for(int i=0; i<N; i++)
{
scanf("%d %d %d", &temp.add, &temp.value, &temp.next);
buf.push_back(temp);
m.insert(make_pair(temp.add, i));
}
}
void sortByValue()
{
sort(list.begin(), list.end());
}
void creatList()
{
// 两种退出情况
// 1. next为null
// 2. 没有找到下一个地址的单元
int pos = head;
while(pos != -1)//如果没有找到null
{
map<int, int>::iterator it=m.find(pos);
if(it != m.end())
{
int index=(*it).second;
list.push_back(buf[index]);
pos = buf[index].next;
}
else
{
break;
}
}
}
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("E:\\in.txt", "r", stdin);
#endif
Input();
creatList();
if(list.size() == 0)
{
printf("0 -1\n");
}
else
{
sortByValue();
head = list[0].add;
printf("%d %05d\n", list.size(), head);
int i;
for(i=0; i<list.size()-1; i++)
{
list[i].next = list[i+1].add;
printf("%05d %d %05d\n", list[i].add, list[i].value, list[i].next);
}
printf("%05d %d -1\n", list[i].add, list[i].value);
}
return 0;
}