题意:把链表中的重复部分拆分出来,相对位置不变。
思路:链表的基本操作。
代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <map>
#include <vector>
#include <set>
using namespace std;
const int MAX_N = 100010;
struct Data {
int add, nxt, v;
}d[MAX_N];
map<string, int> mp;
vector<string> val;
int id(string x) {
if (mp.count(x)) return mp[x];
val.push_back(x);
return mp[x] = val.size()-1;
}
char s1[10], s2[10];
int null, head, head1, head2, p, p1, p2, now1, now2;
int n, v;
set<int> st;
int main() {
// freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
null = id("-1");
scanf("%s %d", s1, &n);
head = id(s1);
for (int i = 0; i < n; i++) {
scanf("%s %d %s", s1, &v, s2);
int id1 = id(s1), id2 = id(s2);
d[id1].add = id1; d[id1].v = v; d[id1].nxt = id2;
}
p2 = now2 = null; head1 = null; head2 = null;
p = head;
p1 = now1 = head1;
while (p != null) {
if (st.count(abs(d[p].v))) {
if (head2 == null) {
head2 = d[p].add;
p2 = now2 = head2;
} else {
d[now2].nxt = d[p].add;
now2 = d[p].add;
}
} else {
if (head1 == null) {
head1 = d[p].add;
p1 = now1 = head1;
} else {
d[now1].nxt = d[p].add;
now1 = d[p].add;
}
st.insert(abs(d[p].v));
}
p = d[p].nxt;
}
d[now1].nxt = null; d[now2].nxt = null;
p1 = head1; p2 = head2;
while (p1 != null) {
printf("%s %d %s\n", val[d[p1].add].c_str(), d[p1].v, val[d[p1].nxt].c_str());
p1 = d[p1].nxt;
}
while (p2 != null) {
printf("%s %d %s\n", val[d[p2].add].c_str(), d[p2].v, val[d[p2].nxt].c_str());
p2 = d[p2].nxt;
}
return 0;
}