PAT 1097. Deduplication on a Linked List (25)(链表问题)(链表分段)

来源:互联网 发布:sql 前几个字符相同 编辑:程序博客网 时间:2024/06/16 10:47

官网

题目

1097. Deduplication on a Linked List (25)

时间限制
300 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue
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

解题思路

  • 1.题目意思是给你一个链表,把链表中值第一次出现的那些链表保存下来,不是第一次出现的统一放在一起,最后分别输出上述俩部分。

AC代码

#include <iostream>  #include <math.h>#include<map>#include<vector>using namespace std;map<int, int> value, nxt;int first, n;int key[10001];vector<int> keep, other;int main(){    cin >> first >> n;    int id, val, nx;    for (int i = 0; i < n; i++)    {        cin >> id >> val >> nx;        value[id] = val;        nxt[id] = nx;    }    int now = first;    while (now!=-1)    {        //如果第一出现就存到keep,否则存到other;        if (key[abs(value[now])]==0)        {            keep.push_back(now);            key[abs(value[now])] = 1;        }        else        {            other.push_back(now);        }        now = nxt[now];    }    //分别输出    for (int i = 0; i < (int)keep.size(); i++)    {        printf("%05d %d", keep[i], value[keep[i]]);        if (i==(int)keep.size()-1)        {            printf(" -1\n");        }        else{            printf(" %05d\n", keep[i + 1]);        }    }    for (int i = 0; i < (int)other.size(); i++)    {        printf("%05d %d", other[i], value[other[i]]);        if (i == (int)other.size() - 1)        {            printf(" -1\n");        }        else{            printf(" %05d\n", other[i + 1]);        }    }    return 0;}
0 0
原创粉丝点击