我想从Java中的LinkedList中删除项目。这个列表是由我实现的,我没有使用任何Java API。我面临的主要问题是RECURSION,因为我总是迷失在递归编码中。在Java中删除LinkedList中的特定项目而不使用任何API
class List{
int N;
List next;
List current;
List(int N){
this.N =N;
this.next = null;
}
@Override
public String toString() {
String o = "";
List curr = this;
while(curr != null){
o += curr.N+"-->";
curr = curr.next;
}
return o+"TAIL";
}
}
方法来实现:
private static List Remove(List L,int N){
if(L == null || L.next == null)
return L;
List current = L;
List previous = null;
while(current != null){
if(current.N == N){
current = current.next;
if(previous == null)previous = current;
else{
previous.next = current;
}
break;
}else{
previous = current;
current = current.next;
}
}
return previous;
}
输入 -
List list1 = new List(1);
list1.next = new List(2);
list1.next.next = new List(3);
list1.next.next.next = new List(4);
list1.next.next.next.next = new List(5);
list1.next.next.next.next.next = new List(6);
list1.next.next.next.next.next.next = new List(7);
System.out.println("Before Removal "+list1.toString());
System.out.println("After Removal "+Remove(list1,3));
输出我得到的是 -
- 取出之前,1 - > 2 - > 3- - > 4 - > 5 - > 6 - > 7 - > TAIL
- 后去除2 - > 4 - > 5 - > 6 - > 7 - > TAIL
这里我失去值1,因为我设置current = current.next
或参考正被设置为下一个值。所以当然,我对存储在不同引用中的数据的表示存在一些问题。
@bunta,请参阅我的更新,希望它可以帮助:-) – 2012-04-25 09:29:52
感谢您的解释 – 2012-04-25 09:31:41