0
点赞
收藏
分享

微信扫一扫

PAT_甲级_1097 Deduplication on a Linked List (25point(s)) (C++)【删除链表重复节点】


目录

​​1,题目描述​​

​​ 题目大意​​

​​2,思路​​

​​3,AC代码​​

​​4,解题过程​​

​​第一搏​​

​​第二搏​​

1,题目描述

PAT_甲级_1097 Deduplication on a Linked List (25point(s)) (C++)【删除链表重复节点】_删除链表重复节点

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

 题目大意

删除链表中的绝对值重复的节点,并将删除的节点顺序链接起来,成为remoList。输出newList和remoList;

 

2,思路

  1. 设计结构体:struct node{
    int add, key, next;
    }data[100010]。下标即地址,模拟链表遍历;
  2. PAT_甲级_1097 Deduplication on a Linked List (25point(s)) (C++)【删除链表重复节点】_甲级_02

  3. map<int, int> record记录每个元素绝对值出现的次数。当次数大于1时加入remoList,否则加入newList中:
  4. PAT_甲级_1097 Deduplication on a Linked List (25point(s)) (C++)【删除链表重复节点】_C++_03

3,AC代码

#include<bits/stdc++.h>
using namespace std;
struct node{
int add, key, next;
}data[100010]; //模拟链表的遍历过程
map<int, int> record; //记录每个元素绝对值出现次数
vector<node> newList, remoList; //newList新链表 remoList删除元素的链表
int main(){
#ifdef ONLINE_JUDGE
#else
freopen("1.txt", "r", stdin);
#endif // ONLINE_JUDGE
int head, N;
scanf("%d %d", &head, &N);
node n;
int add, key, next;
for(int i = 0; i < N; i++){
scanf("%d %d %d", &n.add, &n.key, &n.next);
data[n.add] = n;
}
add = head;
while(add != -1){
record[abs(data[add].key)]++; //absolute value绝对值
if(record[abs(data[add].key)] > 1) //absolute value绝对值
remoList.push_back(data[add]);
else
newList.push_back(data[add]);
add = data[add].next;
}
if(newList.size() > 0){
for(int i = 0; i < newList.size() - 1; i++)
printf("%05d %d %05d\n", newList[i].add, newList[i].key, newList[i+1].add);
printf("%05d %d -1\n", newList[newList.size() - 1].add, newList[newList.size() - 1].key);
}

if(remoList.size() > 0){
for(int i = 0; i < remoList.size() - 1; i++)
printf("%05d %d %05d\n", remoList[i].add, remoList[i].key, remoList[i+1].add);
printf("%05d %d -1", remoList[remoList.size() - 1].add, remoList[remoList.size() - 1].key);
}
return 0;
}

4,解题过程

第一搏

链表问题已经很常见了。

PAT_甲级_1097 Deduplication on a Linked List (25point(s)) (C++)【删除链表重复节点】_PAT_04

第二搏

运行时间短,且是段错误,应该是边界问题,比如head为-1

PAT_甲级_1097 Deduplication on a Linked List (25point(s)) (C++)【删除链表重复节点】_删除链表重复节点_05

PAT_甲级_1097 Deduplication on a Linked List (25point(s)) (C++)【删除链表重复节点】_PAT_06

举报

相关推荐

0 条评论