package mycollection;
/**
- 自定义一个链表
- 增加插入节点
- @author
*/
public class TestLinkedList {
private Node first;
private Node last;
private int size;
public void add(int index,Object obj) {
Node node = new Node(obj);
Node temp = getNode(index);//找到索引位置的节点
size++;
if(temp != null){
if(index == 0){
first = node;
node.next = temp;
temp.previous = node;
}else if(index == size-1){
last = node;
temp.next = node;
node.previous = temp;
}else{
Node up = temp.previous;
up.next = node;
node.previous = up;
node.next = temp;
temp.previous = node;
}
}
}
public void remove(int index){
Node up;
Node down;
Node temp = getNode(index);
if(temp != null){
up = temp.previous;
down = temp.next;
if(up != null){
up.next = down;
}
if(down != null){
down.previous = up;
}
//被删除的元素是第一个时
if(index == 0){
first = down;
}
//被删除的元素是第二个时
if(index == size-1){
last = up;
}
size--;
}
}
//[]
//["a","b","c","d"]
public Object get(int index) {
if(index<0 || index>size-1){
throw new RuntimeException("索引数字不合法"+index);
}
Node temp = getNode(index);
return temp!=null?temp.element:null;
}
public Node getNode(int index){
Node temp;
if(index < (size>>1)){
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;
}
public void add(Object obj) {
Node node = new Node(obj);
if(first == null){
// node.previous = null;
// node.next = null;
first = node;
last = node;
}else{
node.previous = last;
node.next = null;
last.next = node;
last = node;
}
size++;
}
public String toString() {
//[a,b,c] first=a; last=c;
//a,b,c
StringBuilder sb = new StringBuilder();
sb.append("[");
Node temp = first;
while(temp != null){
sb.append(temp.element+",");
temp = temp.next;
}
sb.setCharAt(sb.length()-1, ']');
return sb.toString();
}
public static void main(String[] args) {
TestLinkedList list = new TestLinkedList();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
list.add("e");
System.out.println(list);
System.out.println(list.get(2));
list.remove(0);
System.out.println(list);
list.add(3, "##");
System.out.println(list);
}
}
########################################################
package mycollection;
/**
- @author
*/
public class Node {
Node previous;//上一节点
Node next; //下一节点
Object element;//元素数据
public Node(Node previous, Node next, Object element) {
super();
this.previous = previous;
this.next = next;
this.element = element;
}
public Node(Object element) {
super();
this.element = element;
}
}