2013-03-01 57 views
1

嘿家伙我试图实现单链表的appeed方法时遇到了问题。 这里是代码:单链表添加方法

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 - >>>我得到< | 3> ,但如果我做了后 - 5 >>>>我得到< | 5>删除我的第一个项目。

帮我个忙,请:(

+1

为什么不储存参考尾部元素。会让事情变得更快。 – 2013-03-01 05:27:31

回答

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

这样做是什么 - temp.next is null3已经插入。因此,它会转到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; 
+0

哇,非常感谢它! – Envix 2013-03-01 04:47:04

+0

为什么downvote,这个答案似乎对我?任何解释为什么它是错误的,以便我也可以清除我的疑惑:-) – 2013-03-01 04:47:33

+1

我打算点击检查,但我偶然点击downvote :(对不起,另外1个问题我如何修改我的打印(),以便在最后一个没有逗号的元素?:D – Envix 2013-03-01 04:55:08

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

} 
+0

感谢它的作品:) – Envix 2013-03-01 04:47:29

+0

没问题...我们欢迎您! :) – codeMan 2013-03-01 04:54:59

+0

1个问题我如何修改我的print(),以便在没有逗号的最后一个元素之后? :D – Envix 2013-03-01 05:00:47

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

您不会向节点的下一个部分添加任何内容到新创建的节点,我想你假设'新的LinkInt()'实际上给节点赋一个'null'值给它的'next'部分。 – 2013-03-01 04:49:10