我正在尝试从java中的LinkedList中删除一个项目。这个List是由我实现的,我没有使用任何java API。我面临的主要问题是RECURSION,因为我总是迷失在递归编码中。
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));
我得到的输出是 -
我设置current = current.next
或将参考设置为下一个值时,我将丢失值1。所以我肯定对存储在不同参考文献中的数据的呈现存在一些问题。
答案 0 :(得分:2)
错误在于:
return previous;
如果未删除,则应返回列表的原始头部。以图形方式显示:
N == 3
List Before Removal: 1-->2-->3-->4-->5-->6-->7-->TAIL
At start of iteration 1:
L ^
previous (null)
current ^
No match -> iteration 2:
L ^
previous ^
current ^
No match -> iteration 3:
L ^
previous ^
current ^
Match -> remove current:
List After Removal: 1-->2-->4-->5-->6-->7-->TAIL
L ^
previous ^
current ^
此时返回previous
,您将失去前头元素L
。
对于要删除head元素的情况,您应该在循环之前添加单独的检查。
顺便说一句,你的Remove
方法不是递归的 - 它永远不会自行调用。
答案 1 :(得分:1)
这只是因为你没有返回头部 - 而是先前指向你刚刚“删除”的节点的指针:
static List Remove(final List L, final int N) {
// Base case for null head pointer
final List head = L;
if (head == null)
return head;
// Base case for removing the head
if (head.N == N)
return head.next;
List current = head.next;
List previous = head;
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 head;
}
另外 - 澄清 - 这不是一个递归的解决方案。