I was watching a video on data structures and algorithms offered here
There firstly code for linked list was written as
public class SListNode{
public Object item;
public SListNode next;
public SListNode(Object item,SListNode next){
this.item=item;
this.next=next;
}
public SListNode(Object item){
this(item,null);
}
public void insertAfter(Object item){
next=new SListNode(item,next);
}
public SListNode nth(int position){
if (position==1){
return this;
}
else if ((position<1)|| next==null){
return null;
}
else{
return next.nth(position-1);
}
}
Then the lecturer said that there are two problems associated with this implementation.
1)if X and Y refer to the same list and if a new item was inserted to x , y doesn't get updated.I think this can be checked by
public static void main (String args[]){
SListNode l1=new SListNode("milk",new SListNode(0,new SListNode(1)));
SListNode l2=l1;
l2=new SListNode("soap",l2);
System.out.println(l1.item+ " "+l1.next.item+ " " +l1.next.next.item);
System.out.println(l2.item+ " "+l2.next.item+ " " +l2.next.next.item);
2)when creating an empty list.
Therefore as a solution separate SListClass that maintains head of list was created.
public class SList{
privte SListNode head;
private int size;
public SList(){
head=null;
size=0;
}
public void insertFront(Object item){
head=new SListNode(item,head);
}
}
I don't understand how to work with SList class.
How to create a linked list with this class?
How is SListNode and Slist classes are connected and how can the methods of SlistNode be called from SList?
Also how has this new implementation provide a solution to earlier problem of if X and Y refer to the same list and if a new item was inserted to x , y doesn't get updated.
I am new to programming and Java therefore a clear explanation would be great