2015-05-06 59 views
0

我们通过列表和子列表来查找列表。 我想在列表中删除列表中的第一个子列表。将元素从子列表中移除到列表中

这里是我想要的一个例子:

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); 
     } 
    } 
    } 
} 

感谢您的帮助...

+0

什么位置和PositionList?你在写自己的迭代器吗? – Joel

回答

0

我不知道如果我正确的,但我认为错误是在if()条件,而不是

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

它不应该是

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

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

+0

没有工作......这个错误:显示java.lang.NullPointerException ****错误检测 \t在removeSubList.RemovePositionList.removeSubList(RemovePositionList.java:22) \t在removeSubList.ListUtils.do_check(Tester.java:306 ) \t at removeSubList.Tester.main(Tester.java:42) 线程“main”中的异常java.lang.Error:错误的结果。 (Tester.java:42) – Javi

+0

当你得到一个nullPointerException时,这意味着你没有初始化de对象或在其他的单词的对象是空的,所以检查你的代码,并找到你是否没有留下一个对象为null这是一个例子:Test test1;但如果你没有初始化它,test1将是空的,所以你应该尝试像这样:):test test1 = new Test(); – Arturouu

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; 
} 
+0

我可以做到没有迭代器? – Javi

+0

@Javi我已经更新了我的答案以供每个人使用。 – Sridhar