;
? ? ? ? }
? ? ? ? size ++;
? ? ? ? return true;
? ? }
? ? //插入到第index个的位置
? ? public boolean insert(int index, E e) {
? ? ? ? Node newnode = new Node(e);? //根据需要添加的内容封装为节点
? ? ? ? Node cnode = getNode(index-1);? //得到第index-1个节点
? ? ? ? newnode.next = cnode.next;
? ? ? ? cnode.next = newnode;
? ? ? ? size++;
? ? ? ? return true;
? ? }
? ? //删除第index个节点
? ? public boolean delete(int index) {
? ? ? ? Node prinode = getNode(index-1);? //得到被删除的节点的前一个节点
? ? ? ? Node delnode = prinode.next;? ? //得到被删除的节点
? ? ? ? prinode.next = delnode.next;
? ? ? ? size --;
? ? ? ? return true;
? ? }
? ? //判空
? ? public boolean isEmpty() {
? ? ? ? return size==0 ? true : false;
? ? }
? ? public void destroyList() {
? ? ? ? header = null;
? ? ? ? size = 0;
? ? }
? ?
? ? //输出
? ? public String toString(){
? ? ? ? StringBuilder s = new StringBuilder("[");
? ? ? ? Node temp = header;
? ? ? ? for(int i=0; i < size;i++){
? ? ? ? ? ? s.append(temp.e.toString()+" ");
? ? ? ? ? ? temp = temp.next;? ? ? ? ? ?
? ? ? ? }
? ? ? ? s.append("]");
? ? ? ? return s.toString();
? ? }
}
双链表表示的实现
class TNode{
? ? E e;
? ? TNode prior, next;
? ?
? ? TNode(){}
? ? TNode(E e){
? ? ? ? this.e = e;
? ? ? ? prior = null;
? ? ? ? next = null;
? ? }
}
public class DoubleLinkedList {
? ? private TNode header = null;? //头结点
? ? int size=0;? ? //链表大小
? ?
? ? public DoubleLinkedList(){
? ? ? ? this.header = new TNode();
? ? }
? ?
? ? //尾添加
? ? public boolean addToLast(E e) {
? ? ? ? if(size == 0){
? ? ? ? ? ? header.e = e;
? ? ? ? }else{
? ? ? ? ? ? TNode TNode = new TNode(e);? //根据需要添加的内容封装为节点
? ? ? ? ? ? TNode last = getNode(size); //得到最后一个节点
? ? ? ? ? ? last.next = TNode;
? ? ? ? ? ? TNode.prior=last;
? ? ? ? }
? ? ? ? size ++;
? ? ? ? return true;
? ? }? ?
? ?
? ?
? ? //找到第index个位置的节点
? ? public TNode getNode(int index){
? ? ? ? if(index > size || index < 0){
? ? ? ? ? ? throw new RuntimeException("索引值有错:" + index);
? ? ? ? }
? ? ? ? TNode temp = new TNode();
? ? ? ? temp = header;
? ? ? ? int count =1;
? ? ? ? while(count != index){
? ? ? ? ? ? temp = temp.next;
? ? ? ? ? ? count ++;
? ? ? ? }
? ? ? ? return temp;
? ? }
? ?
? ? //插入到第index个的位置
? ? public boolean insert(int index,E e){
? ? ? ? TNode TNode = new TNode(e);
? ? ? ? TNode cnode = getNode(index-1); //找到第index-1个位置的节点
? ? ? ? TNode.next=cnode.next;
? ? ? ? TNode.prior = cnode;
? ? ? ? cnode.next.prior = TNode;
? ? ? ? cnode.next = TNode;
? ? ? ? size++;
? ? ? ? return true;
? ? }
? ?
? ? //删除第index个节点
? ? public boolean delete(int index){
? ? ? ? TNode delnode = getNode(index);
? ? ? ? delnode.prior.next=delnode.next;
? ? ? ? delnode.next.prior= delnode.prior;
? ? ? ? size--;
? ? ? ? return true;
? ? }
}