Remove duplicates from an unsorted linked list

前端 未结 19 1130
梦如初夏
梦如初夏 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:30

    Below code implements this without needing any temporary buffer. It starts with comparing first and second nodes, if not a match, it adds char at first node to second node then proceeds comparing all chars in second node to char at third node and so on. After comperison is complete, before leaving the node it clears everything that is added and restores its old value which resides at node.val.char(0)

    F > FO > FOL > (match found, node.next = node.next.next) > (again match, discard it) > FOLW > ....

    public void onlyUnique(){
            Node node = first;
            while(node.next != null){
                for(int i = 0 ; i < node.val.length(); i++){
                    if(node.val.charAt(i) == node.next.val.charAt(0)){
                        node.next = node.next.next;
                    }else{
                        if(node.next.next != null){ //no need to copy everything to the last element
                            node.next.val = node.next.val + node.val;
                        }
                        node.val = node.val.charAt(0)+ "";
                    }
                }
                node = node.next;
            }
        }
    

提交回复
热议问题