从列表中构建链接链 [英] Construct chain of links from list

查看:111
本文介绍了从列表中构建链接链的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个键/值对列表,我需要在列表中检测值与键匹配的链。



例如,从下面可以有12,23,34或62,23,34

 关键值
1 2
3 4
2 3
6 2

多个值可以指向相同的密钥,但我需要为每个独特的开始和结束点存储不同的链。这个列表可以以任何顺序。



我使用的是Java,但是我坚持如何解决这个问题。



请帮忙!

解决方案

递归!

  import java.util.HashMap; 
import java.util.Map;

public class Chain
{
private static Map<字符串,字符串>地图;

public static void main(String args [])
{
map = new HashMap< String,String>();

map.put(1,2);
map.put(3,4);
map.put(2,3);
map.put(6,2); (key):map.keySet())

System.out.print((+ key +,+ map.get(key) +));
recurse(map.get(key));
System.out.println();



private static void recurse(String value)
{
if(map.containsKey(value))
{
System.out.print((+ value +,+ map.get(value)+));
recurse(map.get(value));



code
$ b

给你以下输出:

 (3,4)
(2,3)(3,4)
(1, 2)(2,3)(3,4)
(6,2)(2,3)(3,4)


I have a list of key/value pairs and I need to detect chains in the list where the value matches a key.

E.g. from the below there could be 12, 23, 34 or 62, 23, 34

Key  Value
1    2
3    4
2    3
6    2

More than one value can be pointing to the same key but I need to store different 'chains' for each unique start and end point. The list could be in any order.

I'm using Java but am I bit stuck on how to tackle this problem.

Please help!

解决方案

Recursion!

import java.util.HashMap;
import java.util.Map;

public class Chain
{
    private static Map< String , String > map;

    public static void main( String args[] )
    {
        map = new HashMap< String , String >();

        map.put( "1" , "2" );
        map.put( "3" , "4" );
        map.put( "2" , "3" );
        map.put( "6" , "2" );

        for ( String key : map.keySet() )
        {
            System.out.print( "(" + key + "," + map.get( key ) + ")" );
            recurse( map.get( key ) );
            System.out.println();
        }
    }

    private static void recurse( String value )
    {
        if ( map.containsKey( value ) )
        {
            System.out.print( " (" + value + "," + map.get( value ) + ")" );
            recurse( map.get( value ) );
        }
    }
}

Gives you the following output:

(3,4)
(2,3) (3,4)
(1,2) (2,3) (3,4)
(6,2) (2,3) (3,4)

这篇关于从列表中构建链接链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆