int maxSize; //最大长度
int size; //当前长度
Object[] listArray; //对象数组
publicvoiddelete(int index) throws Exception
{
//容错性
if(isEmpty()){
thrownewException("顺序表为空,无法删除!");
}
if(index <0|| index > size -1){
thrownewException("参数错误!");
}
//移动元素(从前往后操作)
for(int j = index; j < size -1; j++)
listArray[j]= listArray[j +1];
listArray[size -1]= null; //注意释放内存(避免内存泄漏)
size--;
}
publicvoid insert(int index,Object obj) throws Exception
{
//容错性
if(size == maxSize){
thrownewException("顺序表已满,无法插入!");
}
if(index <0|| index > size){
thrownewException("参数错误!");
}
//移动元素(从后往前操作)
for(int j = size -1; j >= index; j--)
listArray[j +1]= listArray[j];
listArray[index]= obj;
size++;
} //结点类
publicclassNode{
publicObject data;
publicNode next;
publicNode(Object obj,Node next){
this.data = obj;
this.next = next;
}
}
Node head; //记录头结点信息即可(头结点下标为-1)
int size;
//定位
publicNode locate(int index) throws Exception
{
//容错性
if(index <-1|| index > size)
thrownewException("参数错误!");
//定位到temp指向第index个(index为下标)
Node temp = head;
for(int i =-1; i < index; i++)
if(temp != null)
temp = temp.next;
return temp;
}
publicvoiddelete(int index) throws Exception
{
//容错性
if(isEmpty())
thrownewException("链表为空,无法删除!");
if(index <0|| index > size -1)
thrownewException("参数错误!");
Node temp = locate(index -1); //定位到要操作结点的前一个结点对象
temp.next = temp.next.next;
size--;
}
publicvoid insert(int index,Object obj) throws Exception
{
//容错性
if(index <0|| index > size )
thrownewException("参数错误!");
Node temp = locate(index -1); //定位到要操作结点的前一个结点对象
Node p =newNode(obj,temp.next);
temp.next = p;
size++;
}
//结点类
publicclassNode{
publicObject data;
publicNode next;
publicNode prior;
publicNode(Object obj,Node next,Node prior){
this.data = obj;
this.next = next;
this.prior = prior;
}
}
Node head; //记录头结点信息即可(头结点下标为-1)
int size;
//定位
publicNode locate(int index) throws Exception
{
//容错性
if(index <-1|| index > size)
thrownewException("参数错误!");
//定位到temp指向第index个(index为下标,从0开始)
Node temp = head;
for(int i =-1; i < index; i++)
if(temp != null)
temp = temp.next;
return temp;
}
publicvoiddelete(int index) throws Exception{
if(isEmpty())
thrownewException("链表为空,无法删除!");
if(index <0|| index > size -1)
thrownewException("参数错误!");
Node temp = locate(index -1); //定位到要操作结点的前一个结点对象
temp.next = temp.next.next;
if(temp.next != null) //当删除到最后一个元素:temp.next == null
temp.next.prior = temp;
size--;
}
publicvoid insert(int index,Object obj) throws Exception{
//容错性
if(index <0|| index > size )
thrownewException("参数错误!");
Node temp = locate(index -1); //定位到要操作结点的前一个结点对象
Node p =newNode(obj,temp.next,temp);
temp.next = p;
if(p.next != null) //当插入到最后一个位置:p.next == null
p.next.prior = p;
size++;
}
原文:http://www.cnblogs.com/Doing-what-I-love/p/5533084.html