Linked Listソースの分析
問題があれば、まず自分の書いたコードを貼り付けます。後で詳しい分析を書きます。
package com.zkn.newlearn.collection;
/**
*
* @author zkn 2016-06-25
* LinkedList ,
* , ,
* ,
* 1、
* 2、
* 3、
*
*/
public class ImitateLinkedListTest02<E> {
/**
*
*/
private Node<E> first;
/**
*
*/
private Node<E> last;
/**
* size
*/
private int size;
/**
*
*/
public int size(){
return size;
}
/**
* add
* @param e
*/
public void add(E e){
// add ,
if(last == null){
//
// , null, null
Node<E> newNode = new Node<E>(e,null,null);
// , ,
first = newNode;
last = newNode;
}else{
//
//
// , , null
Node<E> newNode = new Node<E>(e,last,null);
// 。
// ,
//
last.next = newNode;
// ,
last = newNode;
}
size++;
}
/**
*
* , LinkedList , !!!!
* @param size
* @return
*/
public E get(int index){
checkSize(index);
//
// , ,
if(index < (size >> 1)){
// ,
Node<E> node = first;
for(int i=0;i<index;i++){
//
node = node.next;
}
//
return node.item;
}else{
// ,
Node<E> node = last;
for(int i=size-1;i>index;i--){
node = node.prev;
}
return node.item;
}
}
/**
*
* @param size2
*/
private void checkSize(int index) {
if(index >= size || index < 0){
throw new IllegalArgumentException(" , ");
}
}
/**
*
* @author zkn
*
* @param <E>
*/
private static class Node<E>{
//
E item;
//
Node prev;
//
Node next;
public Node(E item, Node prev, Node next) {
this.item = item;
this.prev = prev;
this.next = next;
}
}
public static void main(String[] args){
ImitateLinkedListTest02<String> linkedList = new ImitateLinkedListTest02<String>();
linkedList.add(" ");
linkedList.add(" ");
linkedList.add(" ");
linkedList.add(" ");
System.out.println(linkedList.size());
System.out.println(linkedList.get(2));
}
}