线性表--双链表实现方式 (JAVA) (四)

2014-11-24 11:27:38 · 作者: · 浏览: 13
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开始*/
@Override
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;
this.size = 0;
return true;
}

/** 链表的节点类型 */
class Node {
public T data;
public Node pre;// 便于访问的需要,设置为public
public Node next;

public Node() {
};

public Node(Node pre, T data, Node next) {
this.data = data;
this.pre = pre;
this.next = next;
}
}

}

简单的看看输出结果:

\

对于其具体分析就一个removeData(int index)方法为例吧(index>=1&&index<=size-1)

\