Remove duplicates from an unsorted linked list

前端 未结 19 1096
梦如初夏
梦如初夏 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条回答
  •  -上瘾入骨i
    2020-12-09 07:48

    here are a couple other solutions (slightly different from Cracking coding inerview, easier to read IMO).

    public void deleteDupes(Node head) {
    
    Node current = head;
    while (current != null) {
        Node next = current.next;
        while (next != null) {
            if (current.data == next.data) {
                current.next = next.next;
                break;
            }
    
            next = next.next;
        }
    
        current = current.next;
    }
    

    }

    public void deleteDupes(Node head) {
    Node current = head;
    while (current != null) {
        Node next = current.next;
        while (next != null) {
            if (current.data == next.data) {
                current.next = next.next;
                current = current.next;
                next = current.next;
            } else {
                next = next.next;
            }
        }
    
        current = current.next;
    }
    

    }

提交回复
热议问题