Click here to Skip to main content
15,881,744 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I was watching a video on data structures and algorithms offered

There firstly code for linked list was written as

Java
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

Java
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.

Java
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);
    size++;
    }
}

I don't understand how to work with SList class.
How to create a linked list with this class?If I want to create a new linked list with items 34,"a",100 how is this done?Is it done by
Java
SListNode l_0=new SListNode(34,new SListNode("a",new SListNode(100)));
.If so then how is the connection with head in SList is made with this linked list l_0

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
Posted
Updated 29-Apr-14 5:46am
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900