1097 Deduplication on a Linked List (25 分)
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 Lbeing 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, and Next
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 23854
Sample Output:
00100 21 23854
23854 -15 99999
99999 -7 -1
00000 -15 87654
87654 15 -1
题目大意:
给出一个起始地址以及n结点,随后n行即是结点地址、值以及下个结点的地址。要求将绝对值相同的结点剔除出去,只保留第一个结点。要求输出新链表以及删除的链表。
思路:
静态数组问题:用数组下标作为结点地址,存储值与下个结点的地址。
其次遍历数组,用一个数组作为该结点值是否初次出现, 存入输出链表ans。否则存入删除链表dl。
有个特别重要的,而且容易的忽略的知识点,关于PAT段错误的深层原因:https://blog.csdn.net/qq_42306885/article/details/99606600
参考代码:
#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
struct node{
int v, ad;
}temp[1000000];
vector<node>ans, dl;
bool ft[100000];
int main(){
int st, n;
scanf("%d%d", &st, &n);
for(int i = 0; i < n; ++i){
int ad;
scanf("%d", &ad);
scanf("%d%d", &temp[ad].v, &temp[ad].ad);
}
while(st != -1){
if(!ft[abs(temp[st].v)]){
ft[abs(temp[st].v)] = true;
ans.push_back({temp[st].v, st});
}else dl.push_back({temp[st].v, st});
st = temp[st].ad;
}
for(int i = 0; i + 1< ans.size(); ++i) printf("%05d %d %05d\n", ans[i].ad, ans[i].v, ans[i + 1].ad);
if(ans.size() != 0) printf("%05d %d -1\n", ans[ans.size() - 1].ad, ans[ans.size() - 1].v);
for(int i = 0; i + 1< dl.size(); ++i) printf("%05d %d %05d\n", dl[i].ad, dl[i].v, dl[i + 1].ad);
if(dl.size() != 0) printf("%05d %d -1", dl[dl.size() - 1].ad, dl[dl.size() - 1].v);
return 0;
}