2013-04-26 55 views
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(); 
} 

感谢您的帮助

+0

什么是你的实际任务?它是从链表中移除一个元素吗? – 2013-04-26 02:51:32

+0

是的,我想从链接中删除一个元素,但每次我检查它是相同的 – 2013-04-26 02:52:42

+0

我认为你需要确保你明白什么是“链接列表”实际上是。什么使它连接在一起。当你知道它时,你的任务是从列表中取出一个元素,同时保持所有剩余元素的链接状态。这就像你需要从火车上移除一辆车。 – 2013-04-26 02:56:50

回答

0

您需要更改,以便节点的.next场删除节点,例如w.next = w.next.next从列表中删除w.next节点(因为没有东西指向它了);一定要检查空指针(如果w.next为空,则w.next.next将引发异常)。此外,由于不需要遍历列表的其余部分,所以在if块的末尾添加break语句。

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

测试这个。

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

你总是需要跟踪前一个节点。还有,如果要删除的节点是第一个节点呢?我猜你需要改变,而块看起来像:

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