作者:玻璃里的鱼鱼 | 来源:互联网 | 2023-09-15 20:10
2.1顺序表的插入操作算法publicvoidinsert(inti,Objectx)throwsException{if(curLenlistElem.length)判断顺序表
2.1顺序表的插入操作算法
public void insert(int i,Object x)throws Exception {if(curLen &#61;&#61; listElem.length) //判断顺序表是否已满throw new Exception("顺序表已满"); //抛出异常if(i <0 || i > curlen) //i不合法throw new Exception("插入位置不合法");for(int j &#61; curLen; j > i; j--)listElem[j] &#61; listElem[j-1]; //插入位置及其之后的所有元素后移一位listElem[i] &#61; x; //插入x curLen&#43;&#43;; //表长加一
}
2.2顺序表的删除操作算法
public void remove(int i) throws Exception{if (i<0 || i>curLen - 1) //i不合法 throw new Exception("删除位置不合法"); //抛出异常for (int j &#61; i; j }
2.3顺序表的查找操作算法
public int indexOf(Object x){int j &#61; 0; //j指示顺序表中待比较的元素&#xff0c;其初始值指示顺序表中第0个元素while ( j }
2.6带头结点的单链表上的插入操作算法
public void insert(int i,Object x) throws Exception {Node p &#61; head; //初始化p为头结点&#xff0c;j为计数器int j &#61; -1;while (p !&#61; null && j i - 1 || p &#61;&#61; null) //i不合法throw new Exception("插入位置不合法"); //抛出异常Node s &#61; new Node(x); //生成新结点s.next &#61; p.next; //修改链&#xff0c;使新节点插入单链表中p.next &#61; s;
}
2.8.单链表上的删除操作算法
public void remove(int i) throws Exception {Node p &#61; head; //初始化p指向头结点&#xff0c;j为计数器int j &#61; -1;while(p.next !&#61; null && j i-1 || p.next &#61;&#61; null){throw new Exception("删除位置不合法"); //修改指针&#xff0c;使待删除结点从单链表中脱离出来p.next &#61; p.next.next;
}
3.3求链栈的长度操作算法
public int length() {Node p &#61; top; //初始化&#xff0c;p指向栈顶元素&#xff0c;length为计数器int length &#61; 0; while (p !&#61; null) { //从栈顶元素向后查找&#xff0c;直到p指向空p &#61; p.next; //p指向后继结点&#43;&#43;length; //长度加1}return length;
}
3.4链栈的入栈操作算法
public void push(Object x) {Node p &#61; new Node(x); //构造一个新结点p.next &#61; top;top &#61; p; //新结点成为当前的栈顶结点
}
3.5链栈的出栈操作算法
public Object pop() {if (isEmpty()) {return null;}else {Node p &#61; top; //p指向被删结点&#xff08;栈顶结点&#xff09;top &#61; top.next; //修改链指针&#xff0c;使栈顶结点从链栈中移去return p.data; //返回栈顶结点的数据域的值}
}
3.6循环顺序队列的入队操作算法
public void offer(Object x) throws Exception{if ((rear &#43; 1) % queueElem.length &#61;&#61; front) //队列满throw new Exception("队列已满"); //抛出异常else {queueElem[rear] &#61; x;//x存入rear所指的数组存储位置中&#xff0c;使其成为新的队尾元素rear &#61; (rear &#43; 1) % queueElem.length; //修改队尾指针
}
3.8 链队列的入队操作算法
public void offer(Object x) {Node p &#61; new Node(x); //初始化队列新结点if (front !&#61; null){ //队列非空rear.next &#61; p;rear &#61; p; //改变队尾的位置}elsefront &#61; rear &#61; p;
}
链队列出队poll&#xff08;&#xff09;方法的实现
public Object poll(){if (front !&#61; null) { //队列非空Node p &#61; front; //p指向队首节点front &#61; front.next; //队首节点出列if (p &#61;&#61; rear) //被删除的结点是队尾结点时rear &#61; null;return p.data; //返回队首节点的数据域值}elsereturn null;
}