this.tail = this.head;
} else {
Node newnode = new Node(this.tail, data, null);
this.tail.next = newnode;
this.tail = newnode;
}
this.size++;
// System.out.println(tail.data+""+this.size);
return true;
}
//下表从0开始
@Override
public boolean addData(int index, T element) {
if (index < 0 || index > this.size)
throw new IndexOutOfBoundsException("不能在该位置插入元素,索引越界");
if (this.head == null)
this.addTail(element);// 尾部插入
else {
if (index == 0)
this.addData(element);// 头部插入
else {
Node prev = this.getNode(index - 1);// 找到index-1处的节点
Node next = prev.next;
Node newnode = new Node(prev, element, next);// 分配节点
prev.next = newnode;
next.pre = newnode;
this.size++;
}
}
return true;
}
public String toString() {
if (this.isEmpty())
return "[]";
else {
StringBuffer st = new StringBuffer("[");
for (Node curent = this.head; curent != null; curent = curent.next)
st.append(curent.data.toString() + " ,");
st.append("]");
return st.toString();
}
}
// 反向遍历链表
public String reversetoString() {
if (this.isEmpty())
return "[]";
else {
StringBuffer st = new StringBuffer("[");
for (Node curent = this.tail; curent != null; curent = curent.pre)
st.append(curent.data.toString() + " ,");
st.append("]");
return st.toString();
}
}
/**删除指定位置的结点,下表从0开始*/
public T removeData(int index) {
if (index < 0 || index > this.size - 1)
throw new IndexOutOfBoundsException("不能删除该位置的元素,索引越界");
Node del = null;
if (index == 0) {// 删除的为头节点
del = this.head;
this.head = this.head.next;
this.head.pre = null;
size--;
}
else if(index==size-1)
{
Node prev = this.getNode(index - 1);//找到删除位置的前驱
del = prev.next;//找到要删除的结点
prev.next = del.next;
if (del.next != null)
del.next.pre = prev;
del.pre = null;
del.next = null;
size--;
this.tail.next = null;
this.tail.pre=prev;
this.tail = prev;
}
else {
Node prev = this.getNode(index - 1);//找到删除位置的前驱
del = prev.next;//找到要删除的结点
prev.next = del.next;
if (del.next != null)
del.next.pre = prev;
del.pre = null;
del.next = null;
size--;
}
return null;
}
@Override
public boolean removeTail() {
removeData(this.size-1 );
return false;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
@Override
public boolean clearData() {
this.head = null;
this.tail = null;