经典笔试题-Java代码实现一个链表结构
原创
©著作权归作者所有:来自51CTO博客作者wx5d0241bb88268的原创作品,请联系作者获取转载授权,否则将追究法律责任
代码示例
public class MyList<AnyType> {
private class Node<AnyType>{
public Node<AnyType> pre;
public Node<AnyType> next;
public AnyType data;
public Node(AnyType d, Node<AnyType>p, Node<AnyType> n){}
public Node(){}
}
private int theSize;
private Node<AnyType> Header;
private Node<AnyType> Tail;
public MyList(){}
public void add(AnyType item){}
public boolean isEmpty(){}
public int size(){}
public AnyType get( int idx){}
public void print(){}
}
/*Node<AnyType>类定义了双向链表中节点的结构,它是一个私有类,而其属性和构造函数都是公有的,这样,其父类可以直接访问其属性,而外部类根本不知道Node类的存在。Data是节点中的数据与,pre指向前一个Node节点,next指向后一个Node节点。其构造函数的实现如下,不解释:
View Code*/
public Node(AnyType d, Node<AnyType>p, Node<AnyType> n){
this.data = d;
this.pre = p;
this.next = n;
}
public Node(){
this.data = null;
this.pre = null;
this.next = null;
}
/*下面我们看一下链表的构造函数实现:
View Code*/
public MyList(){
theSize = 0;
Header = new Node<AnyType>(null,null,null);
Tail = new Node<AnyType>(null,Header,null);
Header.next = Tail;
}
/*我们构造了一个带有头、尾节点的双向链表,头节点的Next指向尾节点,为节点的pre指向头节点。链表长度起始为0。
继续贴上链表类其它方法的实现,不解释了,应该比较清楚:*/
//View Code
public void add(AnyType item){
Node<AnyType> aNode = new Node<AnyType>(item,null,null);
Tail.pre.next = aNode;
aNode.pre = Tail.pre;
aNode.next = Tail;
Tail.pre = aNode;
theSize++;
}
public boolean isEmpty(){
return ( theSize == 0);
}
public int size(){
return theSize;
}
public AnyType get( int idx){
if(idx > theSize-1 || idx < 0)
throw new IndexOutOfBoundsException();
Node<AnyType> current = new Node<AnyType>(null,Header,null);
for(int i = 0; i<idx; i++)
current = current.next;
return current.data;
}
public void print(){
Node<AnyType> current = Header.next;
while(current.next != null){
//如果AnyType是你自己定义 //的数据类型,那么请务必提供
//一个toString方法,要么就不
//要在链表里实现print方法。
System.out.println(current.data.toString());
current = current.next;
}
}