PAT 1097 Deduplication on a Linked List (25)

来源:互联网 发布:java爬虫技术视频教程 编辑:程序博客网 时间:2024/05/22 00:05
题目描述
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(感觉自己英语不大好,当时就理解错了,题目意思是移除重复的k的values的绝对值的点).  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.

输入描述:
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.

输出描述:
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.

输入例子:
00100 5
99999 -7 87654
23854 -15 00000
87654 15 -1
00000 -15 99999
00100 21 23854

输出例子:
00100 21 23854
23854 -15 99999
99999 -7 -1
00000 -15 87654

87654 15 -1

一:题目解释

  如果这个点的值的绝对值存在过,则移除,否则保留,这样就将这些点分成俩中类型的点,然后输出即可。

二:解题思路

 我最开始用的不是这个思路,我最开始是想着按顺序输出点,遇到重复的则输出后面的,直到不是重复的为止,然后将这些重复的保存在一个容器中,最后将这个容器输出,后来发现总是会报错,感觉可能是有些情况输出不对吧,后来借鉴了下别人的解体思路:

  从首地址开始找,如果他的特征值的绝对值没有存在过,则将这个点保存在容器一中,否则保存在容器二中,最后分别将这俩个容器中的点输出即可。

三:解题代码

#include<iostream>#include<math.h>#include<vector>using namespace std;int key[100001], _next[100001], visited[10001] = {0};int first, n;vector<int> que1,que2;void _print(vector<int> a){for (int i = 0; i < (int)a.size()-1; i++){printf("%05d %d %05d\n", a[i], key[a[i]], a[i + 1]);}if (!a.empty()){int b = (int)a.size() - 1;printf("%05d %d -1\n", a[b], key[a[b]]);}}int main(){//输入cin >> first >> n;for (int i = 0; i < n; i++){int now;cin >> now;cin >> key[now] >> _next[now];}//从首地址开始遍历,如果他的next为-1,即他是最后一个点了,则退出循环int now=first;while (1){if (visited[abs(key[now])]==0){//如果其特征值的绝对值没存在过,则保存在que1中visited[abs(key[now])] = 1;que1.push_back(now);}else{//如果其特征值的绝对值存在过,则保存在que2中que2.push_back(now);}if (_next[now] == -1)break;now = _next[now];}//分别输出俩个容器中的内容_print(que1);_print(que2);return 0;}


四:总结

    多学学别人的代码吧,必须printf(“%05d”,d)这种,感觉表示起来好方便啊,c有时候输入输出还是蛮方便的。



0 0
原创粉丝点击