如何实现一个支持O(1)时间复杂度的后续操作的堆栈?
答案 0 :(得分:3)
使用LinkedList数据结构以及指向中间元素的额外指针。
此外,您需要另一个变量Var
来存储LinkedList是否具有偶数或奇数元素。
将元素添加到LinkedList的头部。根据{{1}}
更新指向中间元素的指针删除LinkedList的头部。根据{{1}}
更新指向中间元素的指针使用指向中间元素的指针
将下一个元素的值复制到中间,删除下一个元素。以下是更详细的说明:http://www.mytechinterviews.com/singly-linked-list-delete-node
答案 1 :(得分:1)
使用带有指向头部,尾部和中间元素的指针的LinkedList数据结构。
这将为您提供推送,弹出和删除中间元素以及搜索的O(1)时间复杂度。
唯一的技巧是在添加或减去此数据结构中的元素时正确移动“中间”元素指针。
答案 2 :(得分:0)
这是基于数组
的实现/**
* Stack implementation with
* push // push the element at top of stack
* pop // removes and returns the element from top of stack
* findMiddle // returns the element from middle of stack
* deleteMiddle // deletes the element from middle of stack
* @author manjeet
* @param <E>
*/
public class Stack<E> {
private final int size;
private int top;
private E[] elements;
/**
* Constructor with default size
*/
public Stack() {
this(10);
}
public Stack(int s) {
size = s > 0 ? s : 10;
top = -1;
elements = (E[]) new Object[size];
}
/**
* Push element e to stack if it is not full
* @param e
*/
public void push(E e) {
if (top == size - 1){
// if stack is full
System.out.println("Stack is full, cannot push element " + e);
}else{
elements[++top] = e; // place e on Stack
}
}
/**
* pop element from the top of the stack if it is not empty
* @return top of the stack
*/
public E pop() {
E e = null;
if (top == -1){
// if stack is empty
System.out.println("Stack is empty, cannot pop");
}else{
e = elements[top--]; // remove and return top element of Stack
}
return e;
}
/**
* Give middle element of the stack if it is not empty
* @return middle element of the stack
*/
E findMiddle() {
if (top == -1){
System.out.println("Stack is empty, cannot pop");
return null;
}
return elements[top/2];
}
/**
* Delete middle element of the stack if it is not empty
* @return middle element of the stack
*/
E deleteMiddle(){
if (top == -1){
System.out.println("Stack is empty, cannot pop");
return null;
}
int index = (int)top/2;
E middle = elements[index];
System.arraycopy(elements, index+1 , elements, index, (top-index));
top--;
return middle;
}
public static void main(String args[]) {
Stack<Integer> stack = new Stack<Integer>();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
stack.push(6);
stack.push(7);
System.out.println("deleted=" + stack.deleteMiddle());
System.out.println("middle=" + stack.findMiddle());
System.out.println("popped=" + stack.pop());
}
}