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的节点
# 1 楼答案
假设您的“LinearNode”类的工作方式类似于LinkedList,并且具有getPrevious()和getNext()方法: