日期:2014-05-20  浏览次数:20721 次

数据结构算法问题
目前有两个List 
其中一个内容是 1,2,3,4,5,6,7,8,8,9,4,4,10
  另一个内容是 2,3,4,5,6,7,8,9,15,8,16,3,11

其中第一个list是起点 第二个list是终点   比如起点是1  终点是2 , 启动2终点是3  ,起点是3 终点是4 , 启动时4 终点是5, 启点是5  终点是6 , 。。。。。。。。。。
我想通过这两个list查询出以下链路
链路1:1-2-3-4-5-6-7-8-9
链路2:1-2-3-4-16
链路3:1-2-3-4-5-6-7-8-15
链路4:10-11


请问大家有没有好的算法 请提供以下 最好能附上代码。
------最佳解决方案--------------------
其实这是一个图的另一种邻接点的存储方式,可以使用图的深度优先搜索遍历。
package com.tur.demo;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class Route {
    public static List<String> paths = new ArrayList<String>();

    /**
     * 查找元素在数组中的下标,如果找不到,返回-1
     * @param array
     * @param number
     * @param startIndex
     * @return
     */
    public static int indexInArray(int[] array, int number, int startIndex) {
        for (int i = startIndex; i < array.length; ++i) {
            if (array[i] == number) {
                return i;
            }
        }

        return -1;
    }

    /**
     * 把List使用String形式表示
     * @param list
     * @param delimeter
     * @return
     */
    public static String listToString(List<Integer> list, String delimeter) {
        StringBuilder sb = new StringBuilder();
        for (int n : list) {
            sb.append(delimeter);
            sb.append(n);
        }

        return (sb.length() > 0 ? sb.substring(delimeter.length()) : "");
    }

    /**
     * 把路径加到入路径列表,并去掉重复的路径
     * @param path
     */
    public static void addPath(String path) {
        boolean included = false;
        for (int i = 0; i < paths.size(); ++i) {
            String str = paths.get(i);

            if (path.contains(str)) {
                paths.set(i, path);