數據結構之棧應用,和網易大佬的技術面談

程序員小明星 2021-09-18 05:30:03 阅读数:66

大佬
 int num2=0;
for(String str:tokens){
if(str.equals("+")){
num1=stack.pop();
num2=stack.pop();
stack.push(num1+num2);
}else if(str.equals("-")){
num1=stack.pop();
num2=stack.pop();
stack.push(num2-num1);
}else if(str.equals("*")){
num1=stack.pop();
num2=stack.pop();
stack.push(num1*num2);
}else if(str.equals("/")){
num1=stack.pop();
num2=stack.pop();
stack.push(num2/num1);
}else{
stack.push(Integer.parseInt(str));
}
}
return stack.pop();
}

### [](
)1.3用棧實現隊列
[leetcode 232 題](
)
用棧模擬出隊列的push(),pop(),peek(),empty() 方法

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.

class MyQueue {

public Stack<Integer> stack1;
public Stack<Integer> stack2;
/** Initialize your data structure here. */
public MyQueue() {
stack1 =new Stack<>();
stack2 =new Stack<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
stack1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if(stack2.empty()){
while(!stack1.empty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
/** Get the front element. */
public int peek() {
if(stack2.empty()){
while(!stack1.empty()){
stack2.push(stack1.pop());
}
}
return stack2.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return stack1.empty()&&stack2.empty();
}

}

/**

  • Your MyQueue object will be instantiated and called as such:

  • MyQueue obj = new MyQueue();

  • obj.push(x);

  • int param_2 = obj.pop();

  • int param_3 = obj.peek();

  • boolean param_4 = obj.empty();

*/


### [](
)1.4最小棧
[leetcode 155題](
)

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.

class MinStack {

//定義雙棧來實現最小棧
public Deque<Integer> stack1;
public Deque<Integer> minStack;
/** initialize your data structure here. */
public MinStack() {
stack1=new LinkedList<Integer>();
minStack=new LinkedList<Integer>();
minStack.push(Integer.MAX_VALUE);
}
public void push(int val) {
stack1.push(val);
minStack.push(Math.min(val,minStack.peek()));
}
public void pop() {
stack1.pop();

最後

 CodeChina開源項目:【一線大廠Java面試題解析+核心總結學習筆記+最新講解視頻】

數據結構之棧應用,和網易大佬的技術面談_程序員

數據結構之棧應用,和網易大佬的技術面談_程序員_02

數據結構之棧應用,和網易大佬的技術面談_Java_03

數據結構之棧應用,和網易大佬的技術面談_後端_04

數據結構之棧應用,和網易大佬的技術面談_後端_05

數據結構之棧應用,和網易大佬的技術面談_Java_06

由於篇幅原因,就不多做展示了

版权声明:本文为[程序員小明星]所创,转载请带上原文链接,感谢。 https://gsmany.com/2021/09/20210918053003174x.html