4/13学习总结

文章讲述了如何使用单调栈解决寻找循环数组中下一个更大元素的问题,强调了循环数组的特点以及两种处理方式:扩展数组或使用模运算。同时,对比了C++标准库中的栈实现与自定义栈(包括顺序栈和链表栈)的实现方法。
摘要由CSDN通过智能技术生成

今天又复习了一下单调栈对于单调栈的理解更加深刻了。

首先先是关于单调栈的基础代码,这种情况是求较大值的如果要求较小的话把<改为>即可。

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;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值