2024年8月13日 星期二

[1019] Next Greater Node In Linked List

的確是用了stack ! 的確是要存index 再去寫到return array !
不過雙重轉換的部分果然是搞砸了  XD

然後 if else 的部分,倒過來寫就顯得行數比較少這樣XD
但是好好的拆開的寫法 仍舊比較符合我的思考邏輯 QQ
留在code 裡面。以上!
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* nextLargerNodes(struct ListNode* head, int* returnSize) {
int *nodes = calloc (10000, sizeof(int));
int count = 0;
struct ListNode* ptr = head;
while (ptr != NULL)
{
nodes[count++]= ptr->val;
ptr = ptr->next;
}
int *stack = calloc (count, sizeof(int));
int *ret = calloc (count, sizeof(int));
int idx = -1;
//do the stack thing
for (int i=0; i<count; i++)
{
#if 1
while (idx >=0 && nodes[i]> nodes[stack[idx]])
ret[stack[idx--]] = nodes[i];
stack[++idx] = i;
#else
if (idx<0 || nodes[i] <= nodes[stack[idx]] ) //push
stack[++idx] = i;
else // pop & push
{
while (idx >=0 && nodes[i]> nodes[stack[idx]])
ret[stack[idx--]] = nodes[i];
stack[++idx] = i;
}
#endif
}
*returnSize = count;
return ret;
}

沒有留言:

張貼留言