做力扣239的时候,结果一直是如下的错误,但感觉代码并没有问题啊
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
struct node{
int val;
struct node* next;
};
struct queue{
struct node* head;
struct node* end;
};
struct queue* iniqueue(){
struct queue* q=( struct queue*)malloc(sizeof( struct queue));
q->head=q->end=(struct node*)malloc(sizeof(struct node));
q->head->next=NULL;
return q;
}
struct node* addqueue(struct queue* q,int x){
struct node *s=(struct node*)malloc(sizeof(struct node));
s->val=x;
s->next=NULL;
q->end->next=s;
q->end=s;
return s;
}
void dequeue(struct queue* q){
if(q->head->next==NULL)return;
struct node* s=q->head->next;
q->head->next=s->next;
free(s);
s=NULL;
return;
}
int max(int a[],int k){
int s;
for(int i=0;iif(i==0)s=a[0];
else if(a[i]>=a[i-1])s=a[i];
}
return s;
}
void setfree(struct queue*q)
{
struct node* p;
struct node* q1;
q->end=q->head;
p=q->head->next;
q->head->next=NULL;
while(p)
{
q1=p;
p=p->next;
free(q1);
}
return ;
}
int* maxSlidingWindow(int* nums, int numsSize, int k, int* returnSize){
if(k==1)return nums;//直接返还
int i=0;
int n=1;
int *r=(int*)malloc((numsSize-k+1)*sizeof(int));
struct queue*q=iniqueue();
struct node*f;
struct node*g;
//找到第k个节点记录下来
while(1){
if(i==(k-1)){
f=addqueue(q,*(nums+i));
break;
}
else addqueue(q,*(nums+i));
i++;
}
g=q->head;
i=0;
int j=k;
int a[k];
int u;
//记录每k个数的最大值到r中
while(i<(numsSize-k+1)){
u=0;
while(1){
g=g->next;
a[u]=g->val;
if(u==2)break;
u++;
}
dequeue(q);
g=q->head;//更换头部
*(r+i)=max(a,k);
i++;
//更换尾部
while(n){
f=addqueue(q,*(nums+j));
j++;
if(j==(numsSize))n=0;
}
}
setfree(q);
return r;
}
你的主函数呢???你输出右中括号,连左中括号都没输出,说明一开始就不对了
这段代码是用来求滑动窗口内最大值的,首先使用队列结构来存储数据,然后使用max函数来求滑动窗口内的最大值。在dequeue函数中,缺少了释放s节点的操作,应该添加free(s),以及s=NULL;。在setfree函数中,应该将q->head=q->end;而不是q->end=q->head;。