删除索引链表

时间:2013-04-26 02:44:34

标签: java list

您好我试图删除链接列表的一部分链接,但我不知道如何删除链接。当我运行它时,链接仍然存在。如果重要,我使用junit来测试函数。

这是我到目前为止所拥有的。

public void removeAt(int k)
{
   Node w = first;
   int counter = 0; 
   if (k<0 ||  k >= size())
   {
       throw new  IndexOutOfBoundsException("Error ");
   }
   else 
   {
       while (w!= null)
       {
         counter++; 
         if (counter == k)
         {
            Node now = w.next; 
            w= now.next; 
         } 
         w=w.next;
       }
   }
   assert check();
}

感谢您的帮助

5 个答案:

答案 0 :(得分:0)

您需要更改节点的.next字段才能删除节点,例如w.next = w.next.next从列表中删除w.next节点(因为没有任何东西指向它);一定要检查空指针(如果w.next为null,则w.next.next将抛出异常)。另外,在if块的末尾添加break语句,因为不需要遍历列表的其余部分。

答案 1 :(得分:0)

if (counter == k){
    Node now = w.next; 
    w.next= now.next; 
    break;
}

测试一下。

答案 2 :(得分:0)

您正在更新本地变量。您需要做的是更新当前节点之前的链接:

 if (k == 0)
    {
      first = first.next ;
      // you also have to free the memory for first.
    }
    else 
    {  
     Node Last = first ;
     w = first.next ;
     counter = 1 ;
     while (w!= null)
     {
       counter++; // Not sure your conventions, but I think this should be at the end
        if (counter == k)
        {
          last.next = w.next ; /// happily skipping w :)
          // remember you have to free w
          break ; // no point in continuing to the end.

        } 
       w=w.next;
     }
    }
    } 

答案 3 :(得分:0)

您始终需要跟踪上一个节点。而且如果要删除的节点是第一个节点呢?我想你需要改变while块看起来像:

Node l = first;
while (w!= null)
{
    if (counter == k)
    {
        if (w == first)
            first = w.next;
        else    
            l.next = w.next;            
        w.next = null;                  
        break;  
    } 
    l=w;
    w=w.next;
    counter++; 
}

答案 4 :(得分:0)

检查以下代码,从链接列表中删除元素

public void delete(T element){

        if(head != null){  // first check your header node is null or not

            // create two references of your linked list 
            Node<T> tmp = head;    // it will hold current value 
            Node<T> tmp1 = head.getNextRef(); // it will hold next value


            while(true){ // iterate through whole linked list

                if(head.getValue() == element){  // if you found element at first place 
                    head = head.getNextRef();   // then point head to next node of it
                    break;
                }

                if(tmp1.getValue()==element){  // to remove node refer to next of tmp1
                    tmp.setNextRef(tmp1.getNextRef());
                    break;   
                }else{
                    tmp = tmp1;  
                    tmp1 = tmp1.getNextRef();

                    if(tmp1==null)
                        break;
                }
            }
        }
    }