【发布时间】:2018-09-22 17:21:26
【问题描述】:
我正在学习数据结构并尝试理解 Java 中的链表。我的问题是我在递归删除给定索引处的节点时遇到了麻烦。我的目标是得到 O(log n) 而不是使用循环并最终得到 O(n)。
public class LinkedList {
Node head;
int index=0;
Node temp;
Node prev;
public LinkedList(Node head){
this.head=head;
temp=head;
prev=null;
}
public int length(){
int counter=0;
Node n= head.next;
while(n!=null){
counter=counter+1;
n=n.next;
}
return counter;
}
public void push(Node newNode){
newNode.next=head;
head=newNode;
}
public void add(Node prevNode, int value){
if(prevNode==null){
System.out.println("The given previous node can not be null!");
return;
}
Node newNode= new Node(value,null);
newNode.next=prevNode.next;
prevNode.next=newNode;
}
public void add(int index, int value){
length();
if((index<0)||(index>length())){
System.out.println("Array out of bound!");
return;
}
if(index==0){
push(new Node(value,null));
return;
}
Node newNode= new Node(value,null);
Node prevNode=head;
for(int i=1;i<index;i++){
prevNode=prevNode.next;
}
newNode.next=prevNode.next;
prevNode.next=newNode;
}
public void delete(){
head=head.next;
}
public void delete(int index){
if((index<0)||(index>length())){
System.out.println("Array out of bound!");
return;
}
if(index==0){
delete();
return;}
if(head.next==null||head==null){
head=null;
return;}
if(this.index!=index){
this.index++;
prev=temp;
temp=temp.next;
delete(index);
}if(this.index==index){
prev=temp.next;
}
}
public void search(int value){
if(head!=null){
if(value!=head.value){
head=head.next;
index=index+1;
search(value);
}else if(value==head.value){
System.out.println("The value \""+value+"\" was found in index: "+index);}}}
public void display(){
Node n= head;
System.out.print("{");
while(n!=null){
System.out.print(" ("+n.value+") ");
n=n.next;
}System.out.print("}");
System.out.println("\n------------------------------");
}
public static void main(String[]args){
LinkedList ll= new LinkedList(new Node(2,null));
ll.push(new Node(5,null));
ll.push(new Node(6,null));
ll.push(new Node(13,null));
ll.push(new Node(1,null));
ll.display();
ll.add(ll.head.next,8);
ll.display();
ll.add(0, 0);
ll.display();
ll.add(6, 4);
ll.display();
System.out.println(ll.length());
ll.search(13);
ll.delete(2);
ll.display();
}
}
因此,当我尝试删除索引 2 处的条目时,它会删除该索引之前的所有数字,但不会删除该索引处的所有数字 - 所以它会删除 [0] 和 [1] 而不是 [2]。
例如在这段代码中,删除前的数组填充为:{0,1,13,8,6,5,4,2}。
调用delete(2)后,有以下条目:{13,8,6,5,4,2}
我想要的只是删除 13,使数组看起来像这样:{0,1,8,6,5,4,2}
我非常感谢任何改进我的代码的提示。
【问题讨论】:
-
谁说在linkedlist中递归删除是o(logn)?为什么要使用递归?它可以实现简单的迭代,你只是让你的代码难以理解
-
(+, -, *, / , if) 是一步,循环是 n 步,调用函数将是 n 步,因为函数可能包含循环。如果我错了,请纠正我。谢谢
-
我不知道,你在说什么
-
我知道它可以通过迭代来实现,但正如我所说,我想使用递归来提高我的知识
-
你有完整的错误代码。很难说是什么导致了这个特定问题,而不是您应该更喜欢自己调试代码。当然,我可以分享伪代码来实现这一点,既然你提到了,你正在努力提高你的知识。
标签: java recursion linked-list