单链表附加方法

时间:2013-03-01 04:33:17

标签: java add

嘿伙计们,我在尝试实现单链表的附加方法时遇到了麻烦。 这是代码:

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


}

这是我的打印方法(不确定它是否正确):

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

}

继承人的问题:

让我们说3 - &gt;&gt;&gt;我得到&lt; | 3&gt; 但如果我在 - >&gt;&gt;&gt;&gt;之后加上5我得到&lt; | 5&gt;删除我的第一个项目。

请帮帮我:(

3 个答案:

答案 0 :(得分:1)

在这些陈述之后:

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

这样做:

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

tmp.next = tmp1

而不是:

temp.elem = item;

尝试打印方法:

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

}

答案 1 :(得分:0)

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

这样做 - temp.next is null已插入3。因此,它会转到temp.elem = item并覆盖您现有的值。做这样的事情: -

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;

答案 2 :(得分:0)

有这样的方法

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