关于链表add方法的递归实现
在public class LinkedList_Re<A> {
private class Node{
Node next ;
A a ;
public Node(Node next , A a){
this.next = next ;
this.a = a ;
}
public Node(A a){
this(null , a) ;
}
public Node(){
this(null , null) ;
}
public String toString(){
return a.toString() ;
}
}
private class num{
int i = 0 ;
}
private Node dummyHead ;
private int size ;
private num n = new num();
public LinkedList_Re(){
dummyHead = new Node() ;
size = 0 ;
}
public int getSize(){
return size ;
}
public boolean isEmpty(){
return size == 0 ;
}
public void add(int index , A a){
if (index < 0 || index > size)
throw new IllegalArgumentException("Index is illegal!") ;
dummyHead = add(dummyHead , index , a) ;
size ++ ;
}
private Node add(Node node , int index , A a){
n.i = index ;
Node prev = node ;
if (n.i == 0){
prev.next = new Node(prev.next , a) ;
}
if (prev.next == null){
return prev ;
}
n.i = n.i - 1 ;
prev.next = add(prev.next , n.i , a) ;
return prev ;
}
public static void main(String[] args) {
LinkedList_Re one = new LinkedList_Re() ;
one.add(0 , 1) ;
System.out.println(one.dummyHead.next.a);
}
}
因为递归的时候不能用index – ,我就又定义了一个私有类num,将index赋值给num中的int i ,通过操作 i 来实现index – ,总感觉挺麻烦的,有没有地方可以改进的?