简体   繁体   中英

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 :(

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(">");
    }

}
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;

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;  
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM