leetcode-剑指59-II-OK

// 剑指59-II
// language c
// https://leetcode-cn.com/problems/dui-lie-de-zui-da-zhi-lcof/

typedef struct Node{
    int val;
    struct Node* next;
} Node;

// 维护两个队列,一个是队列本身,另一个是单调队列
typedef struct {
    struct Node* head;
    struct Node* tail;
    struct Node* maxhead;
    struct Node* maxtail;
} MaxQueue;

Node* findpre(Node *a,int x){
    if(a->val <x)
        return NULL;
    Node* pre =a;
    a = a->next;
    while(a){
        if(a->val < x)
            break;
        pre = a;
        a = a->next;
    }
    return pre;
}

MaxQueue* maxQueueCreate() {
    MaxQueue* A = (MaxQueue*)malloc(sizeof(MaxQueue));
    A->head = NULL;
    A->tail = NULL;
    A->maxhead = NULL;
    A->maxtail = NULL;
    return A;
}


int maxQueueMax_value(MaxQueue* obj) {
    if(obj->maxhead)
        return obj->maxhead->val;
    return -1;
}


void maxQueuePush_back(MaxQueue* obj, int value) {
    Node *newnode = (Node*)malloc(sizeof(Node));
    newnode->val = value;
    newnode->next = NULL;
    Node *newnodeMAX = (Node*)malloc(sizeof(Node));
    newnodeMAX->val = value;
    newnodeMAX->next = NULL;
    if(obj->head== NULL){
        obj->head =newnode;
        obj->tail =newnode;
        obj->maxhead = newnodeMAX;
        obj->maxtail = newnodeMAX;
    }else{
        obj->tail->next = newnode;
        obj->tail = newnode;
        // 接下来维护另一个队列
        if(value <= obj->maxtail->val){
            obj->maxtail->next = newnodeMAX;
            obj->maxtail = newnodeMAX;
        }else{
            Node *pre = findpre(obj->maxhead,value);
            if(pre){
                pre->next = newnodeMAX;
                obj->maxtail = newnodeMAX;
            }else{
                obj->maxtail = newnodeMAX;
                obj->maxhead = newnodeMAX;
            }
        }
    }

}

int maxQueuePop_front(MaxQueue* obj) {
    if(obj->head == NULL)
        return -1;
    int ans = obj->head->val;
    if(obj->head == obj->tail){
        obj->head = NULL;
        obj->tail = NULL;
        obj->maxtail = NULL;
        obj->maxhead = NULL;
        return ans;
    }else{
        // Node *temp = obj->head;
        obj->head = obj->head->next;
        // free(temp);
        if(ans == obj->maxhead->val)
            obj->maxhead = obj->maxhead->next;
        return ans;
    }
    return -1;
}

void maxQueueFree(MaxQueue* obj) {
    free(obj);
}

/**
 * Your MaxQueue struct will be instantiated and called as such:
 * MaxQueue* obj = maxQueueCreate();
 * int param_1 = maxQueueMax_value(obj);
 
 * maxQueuePush_back(obj, value);
 
 * int param_3 = maxQueuePop_front(obj);
 
 * maxQueueFree(obj);
*/
posted @ 2021-01-27 12:49  RougeBW  阅读(36)  评论(0编辑  收藏  举报