● 232.用栈实现队列
题目描述
解题思路
题目中要求的pop和C++中的pop有区别
c++总的pop会return元素,但是栈中的元素不会删除。题目中是即返回元素,又修改栈中的内容;
class MyQueue {
public:
stack<int> stIn;
stack<int> stOut;
MyQueue() {
}
void push(int x) {
stIn.push(x);
}
int pop() {
int sizeIn = stIn.size();
if(stOut.empty())
{
while(sizeIn--)
{
stOut.push(stIn.top());
stIn.pop();
}
}
int result = stOut.top();
stOut.pop();
return result;
}
int peek() {
int res = this->pop(); // 直接使用已有的pop函数
stOut.push(res); // 因为pop函数弹出了元素res,所以再添加回去
return res;
}
bool empty() {
return stIn.empty() && stOut.empty();
}
};
● 225. 用队列实现栈
题目描述
解题思路
class MyStack {
public:
queue<int> que1;
queue<int> que2; // 辅助队列,用来备份
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
que1.push(x);
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int size = que1.size();
size--;
while (size--) { // 将que1 导入que2,但要留下最后一个元素
que2.push(que1.front());
que1.pop();
}
int result = que1.front(); // 留下的最后一个元素就是要返回的值
que1.pop();
que1 = que2; // 再将que2赋值给que1
while (!que2.empty()) { // 清空que2
que2.pop();
}
return result;
}
/** Get the top element. */
int top() {
return que1.back();
}
/** Returns whether the stack is empty. */
bool empty() {
return que1.empty();
}
};
/**
* 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();
* bool param_4 = obj->empty();
*/
141. 环形链表
题目描述![在这里插入图片描述](https://img-blog.csdnimg.cn/87a02329e15c4518b5312cfb9123df05.png)
解题思路
**为何在进入while循环之前将fast设置为fast= head->next;会超出时间限制? **
进入while之后再设置为fast = fast->next->next 是设置为每轮快指针走两步,而在while之前初始化是先走一步,进入循环之后也是快指针追慢指针的过程,如果有环,就会陷入死循环。所以正确的做法是进入while循环之后
快指针每次走两步,慢指针每次走一步!!!
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *fast = head;
ListNode *slow = head;
while(fast->next&&fast)
{
fast = fast->next->next;
slow = slow->next;
if(fast == slow)return 1;
}
return 0;
}
};