1、接口
package com.zhuzhu.list;
/**
* <p>Title: ZhuzhuList</p>
* <p>Description: 自定义List接口</p>
* @author zhuzhu
* @date 2018年8月12日
*/
public interface ZhuzhuList<E> {
/**
* 返回List包含元素的个数
*/
int size();
/**
* 添加元素
*/
void add(E e);
/**
* 在index 添加元素
*/
void add(int index,E e);
/**
* 安坐标删除元素
*/
void remove(int index);
/**
* 安坐标获取元素
*/
E get(int index);
/**
* 判断List是否为空
*/
boolean isEmpty();
/**
* 清空数组
*/
void clear();
}
2、接口实现类
package com.zhuzhu.linkedlist;
import com.zhuzhu.list.ZhuzhuList;
public class ZhuzhuLinkedList<E> implements ZhuzhuList<E> {
/**
* 头结点
*/
private Node<E> first;
/**
* 尾巴节点
*/
private Node<E> last;
/**
* 节点的个数
*/
private int size;
/**
* 初始化构造方法
*/
public ZhuzhuLinkedList() {
}
/**
* LinkedList 双向链表 数据结构
*/
private static class Node<E>{
E item;
Node<E> next;
Node<E> prev;
Node(Node<E> prev,E element,Node<E> next){
this.item=element;
this.next=next;
this.prev=prev;
}
}
@Override
public int size() {
// TODO Auto-generated method stub
return size;
}
@Override
public void add(E e) {
//得到链表尾部
Node<E> last_=last;
//新建链表
Node<E> newNode= new Node<>(last_, e, null);
//首次添加
if(last_==null) {
first=newNode;
}else {
last_.next=newNode;
}
//更新双向链表
last=newNode;
size++;
}
@Override
public void add(int index, E element) {
if(index<0 || index>size) {
throw new IndexOutOfBoundsException("请您输入正确的索引");
}
if(index==size) {
add(element);
}else {
insertNode(element,node(index));
}
}
private void insertNode(E element,Node<E> e) {
//得到索引preNode
Node<E> preNode=e.prev;
//创建新节点
Node<E> newNode=new Node<>(preNode, element, e);
e.prev=newNode;
if(preNode==null)
first=newNode;
else
preNode.next=newNode;
size++;
}
/**
* 返回index的Node节点
*/
Node<E> node(int index){
//取size的1/2
if(index<size>>1) {
Node<E> node=first;
for(int i=0;i<index;i++) {
node=node.next;
}
return node;
}else {
Node<E> node=last;
for(int i=size-1;i>index;i--) {
node=node.prev;
}
return node;
}
}
@Override
public void remove(int index) {
if(index<0 || index>=size) {
throw new IndexOutOfBoundsException("请您输入正确的索引");
}
Node<E> e=node(index);
if(e==first) {
first=first.next;
}else if(e==last){
last=e.prev;
last.next=null;
}else {
Node<E> preNode=e.prev;
Node<E> nextNode=e.next;
preNode.next=nextNode;
nextNode.prev=preNode;
e=null;
}
size--;
}
@Override
public E get(int index) {
if(index<0 || index>=size) {
throw new IndexOutOfBoundsException("请您输入正确的索引");
}
return node(index).item;
}
@Override
public boolean isEmpty() {
// TODO Auto-generated method stub
return first==null;
}
@Override
public void clear() {
// TODO Auto-generated method stub
for(Node<E> first_=first;first!=null;first=first.next) {
first_.item=null;
first_.next=null;
first_.prev=null;
}
last=null;
first=null;
size=0;
}
}