admin管理员组文章数量:1603440
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, 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
题目大意:
删除链表中重复的元素,输出处理后的链表和被删除的部分。
题目解析:
自己先想了一种方法,一个样例超时,于是借鉴了别人的思路。https://www.liuchuo/archives/2118
具体代码:
#include<iostream>
#include<algorithm>
#include<cstdlib>
using namespace std;
#define MAXN 100005
struct node {
int address;
int key;
int next;
int num=MAXN*2;
}A[MAXN];
bool flag[MAXN];//用以判断key绝对值是否出现
bool cmp(node a,node b){
return a.num<b.num;
}
int main() {
int start,n,len1=0,len2=0,sumlen;
scanf("%d%d",&start,&n);
for(int i=0; i<n; i++) {
int address,key,next;
scanf("%d%d%d",&address,&key,&next);
A[address].address=address;
A[address].key=key;
A[address].next=next;
}
int tmp=start;
while(tmp!=-1) {
int key=abs(A[tmp].key);
if(flag[key]==false){//不用移除
flag[key]=true;
A[tmp].num=len1++;
}
else{
A[tmp].num=MAXN+len2++;
}
tmp=A[tmp].next;
}
sumlen=len1+len2;
sort(A,A+MAXN,cmp);
for(int i=0;i<sumlen;i++){
if(i==len1-1||i==sumlen-1)
printf("%05d %d -1\n",A[i].address,A[i].key);
else
printf("%05d %d %05d\n",A[i].address,A[i].key,A[i+1].address);
}
return 0;
}
本文标签: 链表PATDeduplicationListLinked
版权声明:本文标题:PAT(链表)——1097. Deduplication on a Linked List (25) 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/dianzi/1728419819a1157581.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论