0

嗨,我正在尝试删除链接列表的一部分中的链接,但我不确定如何删除链接。当我运行它时,链接仍然存在。如果这很重要,我会使用 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();
}

谢谢您的帮助

4

5 回答 5

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;
     }
    }
    } 
于 2013-04-26T02:56:47.523 回答
0

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

于 2013-04-26T02:52:13.420 回答
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++; 
}
于 2013-04-26T03:49:57.863 回答
0
if (counter == k){
    Node now = w.next; 
    w.next= now.next; 
    break;
}

测试这个。

于 2013-04-26T02:55:16.847 回答
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;
                }
            }
        }
    }
于 2015-09-08T07:18:32.493 回答