今天又复习了一下单调栈对于单调栈的理解更加深刻了。
首先先是关于单调栈的基础代码,这种情况是求较大值的如果要求较小的话把<改为>即可。
for(i=1;i<=n;i++)
{
while(!s.empty()&&a[s.top()]<a[i])
{
b[s.top()]=a[i];s.pop();
}
s.push(i);
}
503. 下一个更大元素 II - 力扣(LeetCode)
但是对于这道题,这道题,他不是想普通的数组找更大,而是一个循环数组,而不是想普通的一样到最后一个位置,就是循环又到开头在比较,这个时候其实有两种方法,第一种是相当于在重复一个相同数组放在后面eg:{1,2,3}可以弄成{1,2,3,1,2,3}就这个意思,还有一种表示方法,可以通用于各种循环的一种表示方法,i%n这么一种表达式,即使超过数组长度也会自动跳动到对应的位置。
#include<bits/stdc++.h>
using namespace std;
const int N=10000;
int a[N],b[N]={-1};
int n,k,s;
int main()
{
stack<int>s;
cin>>n;
int i;
for(i=1;i<=n;i++){cin>>a[i];}
for(i=1;i<=n;i++)
{
while(!s.empty()&&a[s.top()]<a[i])
{
b[s.top()]=a[i];s.pop();
}
s.push(i);
}
for(i=1;i<=n;i++){cout<<b[i]<<" ";}
return 0;
}
因为刷题数据结构,都是直接用的c++ 容器这些天分批再用c语言复习一下数据结构。
关于栈的话
typedef struct
{
char date[100];
int top;
int bottom;
}stack;
stack *stackcreate() //创立栈
{
stack *p=new stack;
if(p==NULL) return 0;
p->bottom=p->top=0;
return p;
}
void push(stack *p,int e) //入栈
{
p->date[p->top]=e;
p->top++;
}
void pop(stack *p,int e) //出栈
if(p->top!=p->bottom)
{
e=p->date[p->top-1];
p->top--;
}
}
void stackprint(stack *p) /遍历栈
{
while(p->top!=p->bottom)
{
cout<<p->date[p->top-1];
p->top--;
}
}
typedef struct node
{
int date;
struct node *next;
}linkstack1;
linkstack *initstack()
{
linkstack1 *s;
s=new linkstack;
s->next=NULL;
return s;
}
void push1(linkstack *s,int e)
{
linkstack *t;
t=new linkstack;
t->date=e;
t->next=s->next;
s->next=t;
}
void pop1(linkstack *s,int *e)
{
linkstack *t;
if(s->next!=NULL)
{
t=s->next;*e=t->date;
s->next=t->next;
free(t);
}
}
void display(linkstack *s)
{
while(s->next!=NULL)
{
printf("%d ",s->next->date);
s=s->next;
}
}
stack1 *stackcreate()
{
stack1 *p=new stack1;
if(p==NULL) return 0;
p->bottom=p->top=0;
return p;
}