package com.hcy.collection;
/**
* @author hcy
* 自定义LinkedList
*/
class Node{
Node previous;
Node next;
Object element;
public Node(Object element) {
super();
this.element = element;
}
}
public class MyLinkedList {
private Node first;
private Node last;
private int size;
public MyLinkedList() {
// super();
this.first = null;
this.last = null;
}
public int size(){
return size;
}
public void remove(int index){
Node temp = getNode(index);
if(temp != null){
Node up = temp.previous;
Node down = temp.next;
if(up!=null && down!=null){
up.next = down;
down.previous = up;
}
if(up==null){
down.previous = null;
first = down;
}
if(down==null){
up.next = null;
last = up;
}
}
}
public Node getNode(int index){
Node temp = null;
if (index <= (index >> 2)) {
temp = first;
for (int i = 0; i < index; i++) {
temp = temp.next;
}
} else {
temp = last;
for (int i = size - 1; i > index; i--) {
temp = temp.previous;
}
}
return temp!=null?temp:null;
}
public Object get(int index){
if(index<0||index>size-1){
throw new RuntimeException("索引不合法:"+index);
}
Node temp = null;
temp = getNode(index);
return temp.element;
}
public void add(Object element){
Node node = new Node(element);
if(first == null){
first = node;
last = node;
}else{
node.previous = last;
node.next = null;
last.next = node;
last = node;
}
size++;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
Node temp = first;
sb.append("[");
while(temp != null){
sb.append(temp.element+",");
// System.out.println(temp.element);
temp = temp.next;
}
sb.setCharAt(sb.length()-1, ']');
return sb.toString();
}
public static void main(String[] args) {
MyLinkedList list = new MyLinkedList();
// list.add("a");
// list.add("b");
for(int i = 0;i<20;i++){
list.add("a"+i);
}
System.out.println(list);
System.out.println(list.size());
System.out.println(list.get(5));
System.out.println(list.get(13));
list.remove(7);
System.out.println(list);
}
}