java - 如何通过线性节点中的索引使元素出列
问题描述
如果有人可以提供帮助,我很难找到让该方法删除特定索引上的元素的算法
我试过在下面实现一些,但在逻辑上可能是错误的我也得到了javadoc,这样你就知道算法要求什么
/**
* Removes and returns the element that is at place x in the queue.
* Precondition: x must be less than 5, x must be less than size Note:
* indexing from 0: 0 == front element, 1 == second element, etc.
*
* @param x the passed in index of the element to be removed
* @return the element removed from the queue
* @throws EmptyCollectionException if the queue is empty
* @throws InvalidArgumentException if x > 4, or x > size of collection
*
*/
//@Override
public T dequeue(int x) throws EmptyCollectionException, InvalidArgumentException {
// exception throw if queue is empty
if (numNodes == 0) {
throw new EmptyCollectionException("Empty Collection");
}
// exception throw if x > 4 or size
if (x > 4 || x > size()) {
throw new InvalidArgumentException("Invalid x");
}
T result = null;
LinearNode<T> temp = front;
int count;
while (temp != null) {
result = temp.getElement();
if (numNodes == 1) {
front = null;
back = null;
numNodes--;
return result;
}
if (numNodes > 1) {
if (count == x) {
result = result.setNext();
}
x++;
front = temp.getNext();
front.setPrev(null);
numNodes--;
return result;
}
}
删除索引 x 的节点
解决方案
假设您的“LinearNode”类的工作方式类似于 LinkedList 并且具有 getPrevious() 和 getNext() 方法:
public T dequeue(int idx) {
// Any other bounds checks go here
LinearNode<T> curNode = front;
for(int i = 0; i < idx; i++) {
if(curNode.getNext() != null) {
curNode = curNode.getNext();
} else {
// idx is out of bounds
throw new InvalidArgumentException("Index is out of bounds");
}
}
LinearNode<T> previousNode = curNode.getPrevious();
LinearNode<T> nextNode = curNode.getNext();
if(previousNode != null) {
previousNode.setNext(nextNode);
}
if(nextNode != null) {
nextNode.setPrevious(previousNode);
}
if(curNode.equals(front)) {
front = nextNode;
}
if(curNode.equals(back)) {
back = previousNode;
}
return curNode.getElement();
}
推荐阅读
- ubuntu-18.04 - 如何在 Ubuntu 18.04 上编译 pmars-0.9.2?错误:Makefile:116:目标“全部”的配方失败
- java - 在自定义 Spring Boot 登录表单上显示错误登录消息
- linux - 是否可以导出结构符号?
- swift - Firebase 的用户管理产生一个字符串 UID 如何在 Agora.IO 中使用 UID 的字符串值
- javascript - 确定字符串中的第一个和最后一个字符是否为元音,如果它们匹配则返回 true
- python-3.x - Pandas:基于另一列创建一个新列,该列是一个对象列表
- pandas - Pandas Dataframe 中衰减变化的指数移动平均线
- sql - ADO.Net 查询突然停止处理我的查询
- unity3d - 从 Unity 中的不同场景访问变量
- r - 一口气将许多变异变量分解