package com.gyq.Test;
/**
* 类说明 :双向链表的实现
* 描述:TODO
* @author 郭莹棋
* @date 2018年11月23日
*/
public class myLinked {
//第一个节点
private Node first;
//最后一个节点
private Node last;
//链表长度
int size;
class Node{
Node previous;
Object object;
Node next;
public Node() {
}
public Node(Node previous, Object object, Node next) {
super();
this.previous = previous;
this.object = object;
this.next = next;
}
}
//添加一个元素
public void add(Object object) {
Node node = new Node();
if(first == null) {
node.previous = null;
node.object = object;
node.next = null;
first = node;
last = node;
}else {
node.previous = last;
node.object= object;
node.next = null;
last.next= node;
last = node;
}
size++;
}
//检查下标是否正常
public void rangeCheck(int index) {
if(index < 0 || index >= size) {
try{
throw new Exception();
} catch(Exception e) {
e.printStackTrace();
}
}
}
//得到链表长度
public int getSize() {
return size;
}
//得到指定下标的节点
public Node node(int index) {
Node temp = null;
if(first != null) {
temp = first;
for(int i = 0;i < index;i++) {
temp = temp.next;
return temp;
}
}
return null;
}
//得到指定下标节点的值
public Object get(int index) {
Node temp = node(index);
if(temp != null) {
return temp.object;
}
return null;
}
//移除指定下标的节点
public void remove(int index) {
Node temp = node(index);
if(temp != null) {
Node up = temp.previous;
Node down = temp.next;
up.next = down;
down.previous = up;
}
}
//在指定位置添加一个节点
public void add(int index,Object object) {
Node temp = node(index);
Node n = new Node();
n.object = object;
if(temp != null) {
Node up = temp.previous;
up.next = n;
n.previous = up;
n.next = temp;
temp.previous = n;
}
}
public static void main(String[] args) {
myLinked t = new myLinked();
t.add("rch");
t.add("gyq");
t.add("shibi");
//t.remove(1);
System.out.println(t.get(1));
//t.add(1, "sddd");
//System.out.println(t.get(1));
}
}