您的位置:首页 > 编程语言 > Java开发

简单实现Java中的LinkedList

2013-11-26 16:25 134 查看
package com.cym.collection;

public class MyLinkedList {
private Node first ;
private Node last;
private int size;
public void add(Object obj){
Node temp = new Node();
if (first==null) {
temp.setPrevious(null);
temp.setContent(obj);
temp.setNext(null);

first = temp;
last = temp;
}else{
temp.setPrevious(last);
temp.setContent(obj);
temp.setNext(null);

last.setNext(temp);
last = temp;
}
size++;
}
public int size(){
return size;
}
public Object get(int index){
rangeCheck(index);
Node tempNode = node(index);
return tempNode.content;
}

public boolean remove(int index){
rangeCheck(index);
Node tempNode = node(index);

Node prev = tempNode.previous;
Node next = tempNode.next;

//首尾节点检测
if(prev!=null)
prev.setNext(next);
if(next!=null)
next.setPrevious(prev);
size--;//切记
return true;
}

public void add(int index,Object obj){
rangeCheck(index);
Node tempNode = node(index);

Node newNode = new Node();
newNode.setPrevious(tempNode.getPrevious());
newNode.setContent(obj);
newNode.setNext(tempNode.getNext());

Node prev = tempNode.previous;
Node next = tempNode.next;

//首尾节点检测
if(prev!=null)
prev.setNext(newNode);
if(next!=null)
next.setPrevious(newNode);

}

public void set(int index,Object obj){
rangeCheck(index);
Node tempNode = node(index);

tempNode.setContent(obj);

}
private Node node(int index) {
Node tempNode = null;
if (index<size>>1) {
tempNode = first;
for (int i = 0; i < index; i++) {
tempNode = tempNode.next;
}
}else {
tempNode = last;
for (int i = size-1; i >index; i--) {
tempNode = tempNode.previous;
}
}
return tempNode;
}

private void rangeCheck(int initialCapacity) {
if (initialCapacity<0) {
try {
throw new Exception();
} catch (Exception e) {
e.printStackTrace();
}
}

}

}
class Node{
Node previous;
Node next;
Object content;
public Node getPrevious() {
return previous;
}
public void setPrevious(Node previous) {
this.previous = previous;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public Object getContent() {
return content;
}
public void setContent(Object content) {
this.content = content;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: