Java 在索引链接列表中删除
嗨,我正试图删除链接列表中的一部分链接,但我不知道如何删除链接。当我运行它时,链接仍然存在。我使用junit来测试函数,如果这很重要的话 这是我到目前为止所拥有的Java 在索引链接列表中删除,java,list,Java,List,嗨,我正试图删除链接列表中的一部分链接,但我不知道如何删除链接。当我运行它时,链接仍然存在。我使用junit来测试函数,如果这很重要的话 这是我到目前为止所拥有的 public void removeAt(int k) { Node w = first; int counter = 0; if (k<0 || k >= size()) { throw new IndexOutOfBoundsException("Error "); }
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();
}
public void removeAt(int k)
{
节点w=第一;
int计数器=0;
如果(k=size())
{
抛出新的IndexOutOfBoundsException(“错误”);
}
其他的
{
while(w!=null)
{
计数器++;
if(计数器==k)
{
Node now=w.next;
w=现在。下一步;
}
w=w.next;
}
}
断言检查();
}
感谢您的帮助您需要更改节点的
.next
字段以删除节点,例如w.next=w.next。next
从列表中删除w.next
节点(因为不再有任何对象指向它);确保检查空指针(如果w.next
为空,则w.next.next
将引发异常)。另外,在if块的末尾添加一个break
语句,因为不需要遍历列表的其余部分
if (counter == k){
Node now = w.next;
w.next= now.next;
break;
}
测试此项。您正在更新局部变量。您需要做的是在当前节点之前更新链接:
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;
}
}
}
您始终需要跟踪上一个节点。还有,如果要删除的节点是第一个节点呢?我想您需要更改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++;
}
检查从链表中删除元素的以下代码
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;
}
}
}
}
公共作废删除(T元素){
如果(head!=null){//首先检查头节点是否为null
//创建链接列表的两个引用
节点tmp=head;//它将保存当前值
节点tmp1=head.getNextRef();//它将保存下一个值
while(true){//遍历整个链表
if(head.getValue()==element){//if您首先找到了元素
head=head.getNextRef();//然后将head指向它的下一个节点
打破
}
如果(tmp1.getValue()==element){//要删除节点,请参阅tmp1的下一个
tmp.setNextRef(tmp1.getNextRef());
打破
}否则{
tmp=tmp1;
tmp1=tmp1.getNextRef();
如果(tmp1==null)
打破
}
}
}
}
您的实际任务是什么?是要从链接列表中删除元素吗?是的,我正在尝试从链接中删除元素,但每次我检查它时,都是相同的。我认为您需要确保了解链接列表
实际上是什么。是什么让它联系在一起。当您知道这一点时,您的任务将是从列表中删除一个元素,同时保持所有其余元素的链接状态。就像你只需要从火车上卸下一节车厢。