当前位置:网站首页>1019. the next larger node in the linked list

1019. the next larger node in the linked list

2022-06-09 10:11:00 Mr Gao

1019. The next node in the linked list

Given a length of n The linked list of head

For each node in the list , Find the next one Larger nodes Value . in other words , For each node , Find the value of the first node next to it , The value of this node Strictly greater than It's worth .

Returns an array of integers answer , among answer[i] It's No i Nodes ( from 1 Start ) The value of the next larger node . If the first i One node does not have the next larger node , Set up answer[i] = 0
 Insert picture description here
Input :head = [2,1,5]
Output :[5,5,0]
 Insert picture description here
Input :head = [2,7,4,3,5]
Output :[7,0,5,5,0]
The solution code is as follows :

/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */


/** * Note: The returned array must be malloced, assume caller calls free(). */


 struct ListNode* f(struct ListNode* p,int val){
    
     while(p){
    
         if(p->val>val){
    
             return p;
         }
         p=p->next;;
     }
     return NULL;
 }
int* nextLargerNodes(struct ListNode* head, int* returnSize){
    
    int r=0;
    int max=0;
    struct ListNode* p=head;
    struct ListNode* s;
    int len=0;
    while(p){
    
        p=p->next;
        len++;
    }
    * returnSize=len;
     int *arr=(int *)malloc(sizeof(int)*len);
     len=0;
     while(head){
    
         s=f(head->next,head->val);
         if(s){
    
            arr[len++]=s->val;
         }
         else{
    
               arr[len++]=0;
         }
         head=head->next;
     }

return arr;
}
原网站

版权声明
本文为[Mr Gao]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206090927456039.html