Hi Guys,
I have the following insert method and don't know why/how to implement it to correctly add more than one item. And so that if the key of the item is the same as another don't insert it(throw exception). it is a singly linked list - implementation.
public void insert(Item x) throws DuplicateExc {
// references to current and previous node in the list
Node current, previous;
current = first;
previous = null;
while (current != null %26amp;%26amp;
current.element.getCallNumber().compareT... %26lt; 0) {
previous = current;
current = current.next;
}
Node newNode = new Node(x,current);
if(previous == null %26amp;%26amp; first == null){
first = newNode;
} else {
previous.next = newNode;
}
count++;
}
Thanks in advance :)
Duplicates exception in Java Linked List - Please help?
Just modify you program i bit, it will work
public void insert(Item x) throws DuplicateException {
// references to current and previous node in the list
Node current, previous;
current = first;
previous = null;
while (current != null %26amp;%26amp;
current.element. getCallNumber(). compareTo(x.getCallNumber ()) %26lt;= 0) {
previous = current;
current = current.next;
if (current.element. getCallNumber(). compareTo (x.getCallNumber ()) == 0)) throw new DuplicationException ( "Doh i found a duplication");
}
Node newNode = new Node(x,current);
if(previous == null %26amp;%26amp; first == null){
first = newNode;
} else {
previous.next = newNode;
}
count++;
}
Reply:Hi
This is what i understated from you: you want to implement a method that add element only if the key is not repeated and you want to do this is java, here is my code
****************************************...
import java.util.LinkedList;
public class MyLinkedList
{
LinkedList myList = new LinkedList();
public static void main(String[] args)
{
MyLinkedList ml = new MyLinkedList();
ListElement element = new ListElement("1", " Elemnt Number 1");
try
{
ml.addListElement(element);
element = new ListElement("2", " Elemnt Number 2");
ml.addListElement(element);
element = new ListElement("3", " Elemnt Number 3");
ml.addListElement(element);
element = new ListElement("1", " Elemnt Number 4");
ml.addListElement(element);
} catch (Exception e)
{
e.printStackTrace();
}
ml.printList();
}
public void addListElement(ListElement element) throws Exception
{
if(myList.size() == 0)
myList.add(element);
else
{
ListElement current;
for(int i = 0; i%26lt; myList.size(); i++)
{
current = (ListElement) myList.get(i);
if(current.key == element.key)
throw new Exception("Repeated Key");
}
myList.add(element);
}
}
public void printList()
{
ListElement current;
for(int i = 0; i%26lt; myList.size(); i++)
{
current = (ListElement) myList.get(i);
System.out.println("Key: " + current.key + " Value: " + current.value);
}
}
}
class ListElement
{
public ListElement(String k,String v)
{
key = k;
value = v;
}
String key;
String value;
}
sliders
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment