删除传统LinkedList中的重复项

时间:2015-01-31 04:18:46

标签: java linked-list

我知道有更好的方法可以使用hashSets..etc来做到这一点,但我想用旧的方式做到这一点。这是我为消除重复而编写的函数,一个棘手的案例是,如果副本是最后一个节点,我必须为它编写一个特殊情况。我是否正确地做到了这一点,我觉得这太过分了。

// Assume list like this: 0->1->2->3->4->0
//and want to remove 0 in this example
  //O(n^2)
public void removeDuplicatesV1(){
  Node current, itr;
  itr = head;
  if(head !=null){
      while(itr!=null && itr.getNext()!=null){  //ptr1
          current = itr;
          while(current.getNext()!=null){   //ptr2
              if(itr.getItem().equals(current.getNext().getItem())){
                  if(current.getNext().getNext()== null){ //look ahead if last node is a dup
                      current.setNext(null);              
                      break;
                  }
                  else
                      current.setNext(current.getNext().getNext());
              }
              current = current.getNext();
          }
          itr = itr.getNext();
      }
  }

}

1 个答案:

答案 0 :(得分:0)

从第一个while循环中删除itr.getNext()!= null。

// Assume list like this: 0->1->2->3->4->0
//Code below won't remove the last 0
//O(n^2)
public void removeDuplicatesV1(){
  Node current, itr;
  itr = head;
  if(head !=null){
      while(itr!=null ){  //slow ptr for outer loop, will be checked against fast pointer
          current = itr;
          while(current != null && current.getNext()!=null){ //inner loop, current ptr moves  down the list
              if(itr.getItem() == current.getNext().getItem())
                  current.setNext(current.getNext().getNext());
              current = current.getNext();
          }
          itr = itr.getNext();
      }
  }