Given a singly linked list L with integer keys, you are supposed to remove the nodes with duplicated absolute values of the keys. That is, for each value K, only the first node of which the value or absolute value of its key equals K will be kept. At the mean time, all the removed nodes must be kept in a separate list. For example, given L being 21→-15→-15→-7→15, you must output 21→-15→-7, and the removed list -15→15.
Input Specification:
Each input file contains one test case. For each case, the first line contains the address of the first node, and a positive N (<= 105) which is the total number of nodes. The address of a node is a 5-digit nonnegative integer, and NULL is represented by -1.
Then N lines follow, each describes a node in the format:
Address Key Next
where Address is the position of the node, Key is an integer of which absolute value is no more than 104, andNext is the position of the next node.
Output Specification:
For each case, output the resulting linked list first, then the removed list. Each node occupies a line, and is printed in the same format as in the input.
Sample Input:00100 5 99999 -7 87654 23854 -15 00000 87654 15 -1 00000 -15 99999 00100 21 23854Sample Output:
00100 21 23854 23854 -15 99999 99999 -7 -1 00000 -15 87654 87654 15 -1
题目大意
给你一个单链表,链表节点的关键字的绝对值小于10000,将链表中绝对值相同的数,只保留第一个,其他的移到另一个链表中。按顺序输出第一个链表和第二个链表。
题目解析
简单模拟
#include <cstdio>
#include <cmath>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <cstdlib>
#include <climits>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define ll long long
const int MAXN = 100000 + 5;
const int MAXM = 10000 + 5;
const int INF = 0x7f7f7f7f;
const int dir[][2] = {0,1,1,0,0,-1,-1,0};
template <class XSD> inline XSD f_min(XSD a, XSD b) { if (a > b) a = b; return a; }
template <class XSD> inline XSD f_max(XSD a, XSD b) { if (a < b) a = b; return a; }
template <class XSD> inline XSD f_abs(XSD a) { return a<0?(-a):a; }
int head, n;
struct node{
int address, value, next;;
}test;
vector<node> a(MAXN), ans0, ans1;
bool vis[MAXM];
void Dfs(int root){///分割链表
if(!vis[f_abs(a[root].value)]) ans0.push_back(a[root]);
else ans1.push_back(a[root]);
vis[f_abs(a[root].value)]=true;
if(a[root].next!=-1) Dfs(a[root].next);
}
void Getdata(){
memset(vis, false, sizeof vis);
for(int i=0; i<n; i++){
scanf("%d %d %d", &test.address, &test.value, &test.next);
a[test.address]=test;
}
Dfs(head);
}
void Solve(){///输出
for(int i=0; i<ans0.size(); i++){///第一个单链表
if(i+1<ans0.size()) printf("%05d %d %05d\n", ans0[i].address, ans0[i].value, ans0[i+1].address);
else printf("%05d %d -1\n", ans0[i].address, ans0[i].value);
}
for(int i=0; i<ans1.size(); i++){///第二个单链表
if(i+1<ans1.size()) printf("%05d %d %05d\n", ans1[i].address, ans1[i].value, ans1[i+1].address);
else printf("%05d %d -1\n", ans1[i].address, ans1[i].value);
}
}
int main(){
while(~scanf("%d%d", &head, &n)){
Getdata();
Solve();
}
return 0;
}