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 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
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
, 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
自己思路:
-
先创建链表,元素有int address,data,next。bool flag——判断是否为有效结点
-
在删除链表这个环节不知道怎么下手
解决思路:
根据算法笔记上提供的思路,自己将这道题目AC了
-
定义静态链表
此处,定义的order,且让order的初始值等于2*maxn,如果为未删除的有效结点,赋予countValid,删除的有效结点,赋值countRemoved+maxn,定义一个bool isExist[maxn],判定此元素是否出现,我认为前面这些想法是解这道题的关键
2. 初始化
3.统计有效结点个数
4.排序,以order作为排序规则
5.输出
代码
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn = 100001;
//1、定义静态链表
struct Node
{
int address, data, next, order;
//order初始值为2maxn表示均为无效结点
}node[maxn];
bool isExist[maxn];//判断该元速是否已出现过
//排序函数
bool cmp(Node a,Node b){
return a.order < b.order;
}
int main(){
//2、初始化
for (int i = 0; i < maxn; i++)
{
node[i].order = 2 * maxn;
isExist[i] = false;
}
int begin, N;
int countValid = 0, countRemoved = 0;//未被删除的有效结点个数,被删除的有效结点个数
scanf("%d%d", &begin, &N);
//输入
for (int i = 0; i < N; i++)
{
int address;
scanf("%d", &address);
node[address].address = address;
scanf("%d%d", &node[address].data, &node[address].next);
}
//3、统计有效结点
int p = begin;
while (p!=-1)
{
if (!isExist[abs(node[p].data)])//该结点的绝对值在之前没有存在
{
isExist[abs(node[p].data)] = true;
countValid++;
node[p].order = countValid;
}
else //该结点的绝对值在之前存在过
{
countRemoved++;
node[p].order = maxn + countRemoved;
}
p = node[p].next;
}
//4、排序
sort(node, node + maxn, cmp);
//5、输出
int count = countValid + countRemoved;
//输出
for (int i = 0; i < count; i++)
{
if (i != countValid - 1 && i != count- 1)
{
printf("%05d %d %05d\n", node[i].address, node[i].data, node[i + 1].address);
}else
{
printf("%05d %d -1\n", node[i].address, node[i].data);
}
}
system("pause");
return 0;
}