将元素从子列表中删除到列表中

时间:2015-05-06 22:57:57

标签: java arraylist

我们采用列表和子列表来寻找列表。 我想在列表中删除子列表的第一个幻影,如果它在列表中。

这是我想要的一个例子:

removeSubList([3,2,3,4,5,3],[3])  [2,3,4,5,3] 
removeSubList([2,3,4,5,3,4],[3,4])  [2,5,3,4] 
removeSubList([3,2,3,4,7],[3,7])  [2,3,4] 
removeSubList([3,2,3,4,5,3],[])  [3,2,3,4,5,3] 
removeSubList([],[3,7])  [] 
removeSubList(null,[3,7])  null 
removeSubList([3,2,3,4,5,3],null)  [3,2,3,4,5,3]

这是我的代码,我尝试但它不起作用......

public class RemovePositionList<E> {

/**
 * Returns in "list" the previous content of "list" after removing "subList" if it is present in "list"
 *
 * @param  list     (input/output)  The list where search and remove the first occurrence of "subList"
 * @param  subList  (input)         The sub list to search within "list"
 */

public void removeSubList(PositionList<E> list,PositionList<E> subList) {
    Position<E> cursor = list.first();
    Position<E> cursor2 = subList.first();
    while(cursor != null && cursor2 != null){  //comprobamos que ningun elemento es null
        if(cursor.element().equals(cursor2)){
            list.remove(cursor);
        }
        else{
            list.next(cursor);
            list.next(cursor2);
        }
    }
  }
}

感谢您的帮助...

2 个答案:

答案 0 :(得分:0)

我不确定我是否正确,但我认为错误是B = A[:-1] + A[1:] 条件而不是

if()

不应该是

if(cursor.element().equals(cursor2))

.............. :)

答案 1 :(得分:0)

我采用了不同的方法来制作您提供的样本输入。它适用于所有情况。

public static void main(String[] args) {
    Integer listElements[] = {3,2,3,4,7};
    Integer subListElements[] = {3,7};

    List<Integer> list = new LinkedList<Integer>(Arrays.asList(listElements));
    List<Integer> subList = Arrays.asList(subListElements);
    System.out.println(removeSubList(list, subList));
}

private static List<Integer> removeSubList(List<Integer> list, List<Integer> subList){
    if(list == null || list.isEmpty() || subList == null){
        return list;
    }
    for(Integer item : subList){
        list.remove(item);
    }
    return list;
}