# JAVA数据结构

> 来源：梦飞idc云平台 | 原文：https://www.mfisp.com/21944.html | 发布：2023-07-11 | 更新：2023-07-11 | 分类：建站教程

**2.1顺序表的插入操作算法**

 

**public void insert(int i,Object x)throws Exception {  
 if(curLen == listElem.length) //判断顺序表是否已满  
 throw new Exception("顺序表已满"); //抛出异常  
 if(i < 0 || i > curlen) //i不合法  
 throw new Exception("插入位置不合法");  
 for(int j = curLen; j > i; j--)  
 listElem[j] = listElem[j-1]; //插入位置及其之后的所有元素后移一位  
 listElem[i] = x; //插入x   
 curLen++; //表长加一  
}**

 

**2.2顺序表的删除操作算法**

 

**public void remove(int i) throws Exception{  
 if (i<0 || i>curLen - 1) //i不合法   
 throw new Exception("删除位置不合法"); //抛出异常  
 for (int j = i; j < curLen - 1; j++)  
 listElem[j] = listElem[j + 1];  
 //被删除元素之后的所有数据元素左移一个存储单位  
 curLen--; //表长-1  
}**

 

**2.3顺序表的查找操作算法**

 

**public int indexOf(Object x){  
 int j = 0; //j指示顺序表中待比较的元素，其初始值指示顺序表中第0个元素  
 while ( j < curLen && !listElem[j].equals(x)) //依次比较  
 j++;  
 if (j < curLen) //判断j的位置是否在顺序表中  
 return j; //返回值为x的数据元素在顺序表中的位置  
 else  
 return - 1; //值为x的数据元素在顺序表中不存在  
}**

 

**2.6带头结点的单链表上的插入操作算法**

  

**public void insert(int i,Object x) throws Exception {  
 Node p = head; //初始化p为头结点，j为计数器  
 int j = -1;  
 while (p != null && j < i - 1) { //寻找第i个节点的前驱  
 p = p.next;  
 ++j; //计数器的值增1  
 }  
 if (j > i - 1 || p == null) //i不合法  
 throw new Exception("插入位置不合法"); //抛出异常  
 Node s = new Node(x); //生成新结点  
 s.next = p.next; //修改链，使新节点插入单链表中  
 p.next = s;  
}**

---
本页由 梦飞idc云平台（https://www.mfisp.com）提供。站点导航见 https://www.mfisp.com/llms.txt
