Remove duplicates from an unsorted linked list

前端 未结 19 1142
梦如初夏
梦如初夏 2020-12-09 06:54
import java.util.*;
/*
 *  Remove duplicates from an unsorted linked list
 */
public class LinkedListNode {  
    public int data;  
    public LinkedListNode next;          


        
19条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-09 07:28

    1. The solution you have provided does not modify the original list.
    2. To modify the original list and remove duplicates, we can iterate with two pointers. Current: which iterates through LinkedList, and runner which checks all subsequent nodes for duplicates.
    3. The code below runs in O(1) space but O(N square) time.

      public void deleteDups(LinkedListNode head){

      if(head == null)
          return;
      
      LinkedListNode currentNode = head;       
      while(currentNode!=null){
          LinkedListNode runner = currentNode;
          while(runner.next!=null){
              if(runner.next.data == currentNode.data)
                  runner.next = runner.next.next;
              else
                  runner = runner.next;
          }
          currentNode = currentNode.next;
      }
      

      }

    Reference : Gayle laakmann mcdowell

提交回复
热议问题