您的位置:首页 > 职场人生

LeetCode高频面试60天打卡日记Day01

2020-03-08 13:31 1096 查看

Day01


Idea:
1、维护两个队列 q1接收输入数据 q2作为输出队列
2、push操作,q1接收新来的数据,再将q2中存放的元素全部加入q1,此时q1 = new data + q2 data
3、将q1 和 q2的引用交换,始终保证q1为空接收新来数据

class MyStack {
private Queue<Integer> q1; //输入
private Queue<Integer> q2; //输出
private int top;
/** Initialize your data structure here. */
public MyStack() {
q1 = new LinkedList<Integer>();
q2 = new LinkedList<Integer>();
}

/** Push element x onto stack. */
public void push(int x) {
q1.offer(x); //q1接收数据,将q2中所有数据复制到q1,保证先来的数据在后面,新来的数据在前面
while(!q2.isEmpty()){
q1.offer(q2.poll());
}
Queue temp = q1;
q1 = q2;
q2 = temp;
}

/** Removes the element on top of the stack and returns that element. */
public int pop() {
return q2.poll();
}

/** Get the top element. */
public int top() {
return q2.peek();
}

/** Returns whether the stack is empty. */
public boolean empty() {
return q2.isEmpty();
}
}

/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/
  • 点赞
  • 收藏
  • 分享
  • 文章举报
YoungNUAA 发布了14 篇原创文章 · 获赞 0 · 访问量 224 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: