This may be a dumb question as I am not majoring in the computer. I am reading Cracking the coding interview and it has the following codes.
But Java (in eclipse) cannot recognize LinkedListNode
but it recognize LinkedList
.
Am I supposed to create a class name LinkedListNode
, a double linked list? Shouldn't java already have that in import java.util.*
as it does for LinkedList
?
import java.util.*;
public static void deleteDups2(LinkedListNode head) {
if (head == null) return;
LinkedListNode previous = head;
LinkedListNode current = previous.next;
while (current != null) {
LinkedListNode runner = head;
while (runner != current) { // Check for earlier dups
if (runner.data == current.data) {
LinkedListNode tmp = current.next; // remove current
previous.next = tmp;
current = tmp; // update current to next node
break; // all other dups have already been removed
}
runner = runner.next;
}
if (runner == current) { // current not updated - update now
previous = current;
current = current.next;
}
}
}
LinkedListNode
isn't a class included with Java. The "Code Library" section (section XI) in the back of the book contains the implementation of LinkedListNode
.
I would include the code here, but the copyright notice in the book doesn't allow for that.
Using the existing LinkedList in java it is quite straight forward to implement this solution, maybe author wants to empathies more on the concept of LinkedList so they have their own implementation as LinkedListNode.
However, this sample code below uses Java's Built in LinkedList to remove the duplicates:
package com.linkedlist;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.LinkedList;
public class RemDupUnsortedLL
{
public static void deleteDups(LinkedList node)
{
HashSet<Integer> set = new HashSet<Integer>();
LinkedList previous=new LinkedList();
int i=0;
while(node.getLast() !=null && i < node.size())
{
int elem = (int) node.get(i);
if(! set.contains(elem)){
set.add((Integer) node.get(i));
previous.add(node.get(i));
}
i++;
}
System.out.print("\n After function call ");
for(int j=0;j<previous.size();j++) {
System.out.print(" " +previous.get(j));
}
}
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.add(1);
list.add(2);
list.add(3); list.add(4); list.add(4);
list.add(4); list.add(5); list.add(6);
System.out.print("Before function call ");
for(int i=0;i<8;i++) {
System.out.print(" " +list.get(i));
}
deleteDups(list);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With