栈的压入、弹出序列
方法:模拟法
直接模拟即可。因为弹出之前的值都会先入栈,所以这里用个栈来辅助。
#include <vector>
#include <stack>
#include <iostream>
using namespace std;
/**
* @brief 给出一个入栈序列pushV和出栈序列popV, 判断出栈序列是否满足条件.
* @param pushV 栈的压入顺序.
* @param popV 是否可能为该栈的弹出顺序.
*/
bool IsPopOrder(vector<int> pushV, vector<int> popV)
{
stack<int> st;
int i = 0, j = 0;
while (i < pushV.size())
{
/* code */
if (pushV[i] != popV[j]){
st.push(pushV[i++]);
}else{
++i, ++j;
while (!st.empty() && st.top() == popV[j])
{
/* code */
st.pop();
++j;
}
}
}
return st.empty();
}
int main()
{
cout << IsPopOrder({1,2,3,4,5}, {4,5,1,2,3}) << endl;
return 0;
}
/**
* @brief 给定一个单链表,删除单链表中重复的值。.
* @param pHead 栈的压入顺序.
*/
ListNode *deleteDuplication(ListNode *pHead)
{
ListNode *vhead = new ListNode(-1);
vhead->next = pHead;
ListNode *pre = vhead, *cur = pHead;
while (cur){
if (cur->next && cur->val == cur->next->val){
cur = cur->next;
while (cur->next && cur->val == cur->next->val){
cur = cur->next;
}
cur = cur->next;
pre->next = cur;
}
else
{
pre = cur;
cur = cur->next;
}
}
return vhead->next;
}