Envix
Envix

Reputation: 15

Singly linked list append method

hey guys i am having trouble trying to implement the appened method for singly linked list. here is the code:

public void append ( int item ) {
//inserts item to the end of the list
        if ( head == null){
            head = new LinkInt();
            curr = head;
            curr.elem = item;
        }
        else{
        LinkInt temp = head;
        while ( temp.next != null){
        temp = temp.next;}
        temp.elem = item;
        }


}

and here is my print method ( not sure if its correct as well ):

public void print () {
//outprint the array 
    //ie. <1, 2, |3, 4>
    if (  head == null) {
        System.out.print("<");
        System.out.print(">");
    }
    else{
    LinkInt temp = head;
    System.out.print("<");
    while ( temp != null) {
        if ( temp == curr){
                System.out.print( "|" + temp.elem + ","); }
        else{
        System.out.print( temp.elem );
        System.out.print(",");}
        temp = temp.next;
    }
    System.out.print(">");
    }
}

}

heres the problem:

let say appened 3 ->>> i get <|3> but if i do appened 5 after ->>>> i get <|5> which delete my first item.

Help me out please :(

Upvotes: 1

Views: 7513

Answers (3)

codeMan
codeMan

Reputation: 5758

after these statement :

while ( temp.next != null)
{
    temp = temp.next;
}

do this:

tmp1= new LinkInt();
tmp1.elem = item;
tmp1.next = null

tmp.next = tmp1

instead of this:

temp.elem = item;

try this for print method:

public void print () 
{
    //outprint the array 
    //ie. <1, 2, |3, 4>
    if (  head == null) 
    {
        System.out.print("<");
        System.out.print(">");
    }
    else
    {
        LinkInt temp = head;
        System.out.print("<");
        while ( temp->next != null) 
        {
            System.out.print( "|" + temp.elem + ","); 
            temp = temp.next;
        }
        System.out.print("|" + temp.elem);}
        System.out.print(">");
    }

}

Upvotes: 1

asifsid88
asifsid88

Reputation: 4701

Have the method this way

public void append(int item)  
{  
    LinkInt l = new LinkInt();  
    l.elem = item;  
    if ( head == null )  
        head = l;  
    else {  
        LinkInt tmp = head;  
        while ( tmp.next != null)  
            tmp = tmp.next;  
        tmp.next = l;  
}

Upvotes: 0

Rahul
Rahul

Reputation: 45060

LinkInt temp = head;
while ( temp.next != null){
    temp = temp.next;
}
temp.elem = item;

What this does is - temp.next is null when 3 is already inserted. Hence, it goes to temp.elem = item and overwrites your existing value. Do something like this:-

LinkInt temp = head;
while ( temp.next != null){
    temp = temp.next;
}
//temp.elem = item; -Not needed.

temp1= new LinkInt();
temp1.elem = item;
temp1.next = null;
temp.next = temp1;

Upvotes: 0

Related Questions