# [LeetCode 503. Next Greater Element II](https://leetcode.com/problems/next-greater-element-ii/) ![](https://i.imgur.com/CARTbxy.png) ### Struct define ```c= typedef struct node{ int val; struct node* next; }node; ``` ### 1. 建立obj並初始化 ```c= node* obj = malloc(sizeof(list)); obj->val = 0; obj->next = NULL; node* head = obj; ``` ### 2. 把nums讀入obj裡面 ```c= for(int i = 0; i < numsSize; i++){ obj->val = nums[i]; if(i != numsSize - 1){ obj->next = malloc(sizeof(list)); obj = obj->next; } } ``` ### 3. 將最後一個node接到第一個node上並歸位obj ```c= obj->next = head; obj = head; ``` ### 4. 開始依序尋找下一個大於該位數的值 ```c= for(int i = 0; i < numsSize; i++){ node* cur = obj->next;; while(true){ if(cur == obj){ //return -1 when finish searching all the elements res[i] = -1; break; } if(cur->val > nums[i]){ //return the current value which is greater than the comparison one res[i] = cur->val; break; } cur = cur->next; } obj = obj->next; } ``` ### 5. 設定回傳陣列大小並回傳陣列 ```c= *returnSize = numsSize; return res; ``` :::spoiler Raw Code ```c= typedef struct node{ int val; struct node* next; }node; int* nextGreaterElements(int* nums, int numsSize, int* returnSize){ node* obj = malloc(sizeof(node)); obj->val = 0; obj->next = NULL; node* head = obj; for(int i = 0; i < numsSize; i++){ obj->val = nums[i]; if(i != numsSize - 1){ obj->next = malloc(sizeof(node)); obj = obj->next; } } obj->next = head; obj = head; int* res = malloc(sizeof(int) * numsSize); for(int i = 0; i < numsSize; i++){ node* cur = obj->next;; while(true){ if(cur == obj){ res[i] = -1; break; } if(cur->val > nums[i]){ res[i] = cur->val; break; } cur = cur->next; } obj = obj->next; } *returnSize = numsSize; return res; } ``` :::