Deduplication on a Linked List (25)

版权声明:本文章由BlackCarDriver原创,欢迎评论和转载 https://blog.csdn.net/BlackCarDriver/article/details/88978149

题目连接: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.

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

大意
给出一堆能够形成一条链的节点,每个节点包含自身地址,节点值,下一个节点值的几个信息。要求将这条链拆分成两条,规则是第一条链中的节点值的绝对值不可以重复出现。

分析
很简单的一道题,注意有些规则题目不用讲明白,要在输入样例中分析出来

My Code

#include<iostream>
#include<stdio.h>
#include<stdio.h>
#include<string>
using namespace std;
const int maxn = 100000 + 9;
int val[maxn];	//地址为i对应的节点的值
int nexta[maxn];	//地址为i的节点的下一个节点的地址
bool set[maxn];		//判断一个值是否已经出现过
//int state[maxn];	//表示这个节点用或不用
int start, num;
using namespace std;

void printList(int head){
	while (head != -1){
		if(nexta[head]!=-1)printf("%05d %d %05d\n", head, val[head], nexta[head]);
		else printf("%05d %d %d\n", head, val[head], nexta[head]);
		head = nexta[head];
	}
}

int main(){
	cin >> start >> num;
	for (int i = 0; i < num; i++){
		int a, v, n;
		scanf("%d%d%d", &a, &v, &n);
		val[a] = v;
		nexta[a] = n;
		//state[a] = -1;
	}
	int nowat = start;
	int firstuse, firstunuse;
	int lastuse = -1, lastunuse = -1;	//上一个采用,不采用的节点
	while (nowat != -1){
		if (!set[abs(val[nowat])]){//第一次遇到这个值的绝对值	
			set[abs(val[nowat])] = true;	//加入已有值集合
			if (lastuse != -1){
				nexta[lastuse] = nowat;
			}
			else{	//第一取值时记录头节点
				firstuse = nowat;
			}
			lastuse = nowat;
		}
		else {
			//state[nowat] = 2;
			if (lastunuse != -1){
				nexta[lastunuse] = nowat;
			}
			else{	//记录第一个不去用的节点地址
				firstunuse = nowat;
			}
			lastunuse = nowat;
		}
	nowat = nexta[nowat];
	}
	nexta[lastuse] = nexta[lastunuse] = -1;
	printList(firstuse);
	printList(firstunuse);
	return 0;
}


猜你喜欢

转载自blog.csdn.net/BlackCarDriver/article/details/88978149