LinkedList的自定义实现

时间:2021-03-03 19:41:00

一、背景              

LinkedList双向链表;

代码:

Node.java:

package com.cy.collection;

public class Node {
Node previous; //上一个node
Object obj; //node上值
Node next; //下一个node public Node(Object obj) {
this.obj = obj;
}
}

LinkedList.java:

package com.cy.collection;

/**
* 自定义实现链表LinkedList
*/
public class LinkedList {
private Node head;
private Node tail;
private int size; //add
public void add(Object obj){
Node n = new Node(obj);
if(head==null){
head = n;
tail = n;
}else{
n.previous = tail;
tail.next = n;
tail = n;
}
size++;
} //在指定下标位置,插入值
public void add(int index, Object obj){
rangeCheck(index); Node temp = node(index);
Node newNode = new Node(obj); if(temp!=null){
Node up = temp.previous;
if(up==null){ //如果是在head节点前面插入
newNode.next = temp;
temp.previous = newNode;
head = newNode;
}else{
up.next = newNode;
newNode.previous = up; newNode.next = temp;
temp.previous = newNode;
}
size++;
}
} //get
public Object get(int index){
rangeCheck(index); Node temp = node(index);
if(temp!=null){
return temp.obj;
} return null;
} public void remove(int index){
Node temp = node(index); if(temp!=null){
Node up = temp.previous;
Node down = temp.next; if(up==null){ //如果remove的是head节点
down.previous = null;
head = down;
}else if(down==null){ //如果remove的是tail节点
up.next = null;
tail = up;
}else{ //remove的是中间节点
up.next = down;
down.previous = up;
}
size--;
}
}

   //找到指定位置index的node
public Node node(int index){
Node temp = null;
if(head!=null){
if(index < (size>>1)){ //从head开始遍历
temp = head;
for(int i=0;i<index;i++){
temp = temp.next;
}
}else{ //从tail开始遍历
temp = tail;
for(int i=size-1;i>index;i--){
temp = temp.previous;
}
}
}
return temp;
} //size
public int size(){
return size;
} //range check
public void rangeCheck(int index){
if(index<0 || index>=size){
throw new RuntimeException("IndexOutOfBoundsException");
}
}
}

Test.java测试:

package com.cy.collection;

public class Test {

    public static void main(String[] args) {
LinkedList list = new LinkedList();
list.add("aaa");
list.add("bbb");
list.add("ccc"); System.out.println(list.size()); list.add(2, "ddd"); System.out.println(list.get(3));
System.out.println(list.size());
} }

输出:

3
ccc
4