Need Help with determining the problem in my Code
I'm trying to implement a linked-list ADT for my lab course. So far, I can't figure out what am I doing wrong. After successful compilation I try to add some more objects and nodes, but after inserting the second element (the first one is created just fine) into the second object and trying to link those two I get an exception message shown below:
--------------------------------------------------------
Quote:
Empty List
Command: +1
Insert 1
1
Command: +2
Insert 2
Exception in thread "main" java.lang.NullPointerException
at SList.insert(SList.java:54)
at TestSList.main(TestSList.java:78)
--------------------------------------------------------
I'll now provide all the necessary codes for the above, but as you can see, my showstructure code is wrong too as, it doesn't show the whole list at the same time, it just shows 1 element at a time, so I'd appreciate it, if anyone could help me to figure out my mistakes here. Thanks in advance.
------------------------------------------------------
Quote:
public void insert(Object newElement){
if (!isFull() && newElement!=null){
if (head==null && cursor ==null)
{
head = new SListNode(newElement, null);
cursor=head;
}
else{
if (cursor==head){
cursor = cursor.getNext();
cursor = new SListNode(newElement, cursor.getNext());
}
}
}
}
------------------------------------------------------
Quote:
public void showStructure(){
if (isEmpty())
System.out.print("Empty List");
else{
SListNode b;
if (head==cursor)
System.out.println(cursor.getElement());
else{
for (b=head; b!=null; b=b.getNext()){
System.out.print(b.getElement());
}
}
}
}
--------------------------------------------------------------
I'll be waiting for your replies.
A linked-list is never full.
A suspicious part of your code (the first line below)
tests if the list is not full:
if (!isFull() && newElement!=null)
A linked-list can never be full (theoretically), so
maybe that test should be renamed, or just thrown
out.
Code:
public void insert(Object newElement){
if (!isFull() && newElement!=null){
if (head==null && cursor ==null){
head = new SListNode(newElement, null);
cursor=head;
}
else{
if (cursor==head){
cursor = cursor.getNext();
cursor = new SListNode(newElement, cursor.getNext());
}
}
}
}