publicclassSolution { publicint[] NextLargerNodes(ListNode head) { IList<int> ans = new List<int>(); Stack<int[]> stack = new Stack<int[]>();
ListNode cur = head; int idx = -1; while (cur != null) { ++idx; ans.Add(0); while (stack.Count > 0 && stack.Peek()[0] < cur.val) { ans[stack.Pop()[1]] = cur.val; } stack.Push(newint[]{cur.val, idx}); cur = cur.next; }
return ans.ToArray(); } }
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution: defnextLargerNodes(self, head: Optional[ListNode]) -> List[int]: ans = list() s = list()
cur = head idx = -1 while cur: idx += 1 ans.append(0) while s and s[-1][0] < cur.val: ans[s[-1][1]] = cur.val s.pop() s.append((cur.val, idx)) cur = cur.next return ans
typedefstructPair { int first; int second; } Pair;
int* nextLargerNodes(struct ListNode* head, int* returnSize) { int len = 0; structListNode* cur = head; while (cur) { cur = cur->next; len++; } int* ans = (int *)calloc(len, sizeof(int)); Pair stack[len]; int top = 0, pos = 0;
cur = head; int idx = -1; while (cur) { ++idx; ans[pos++] = 0; while (top > 0 && stack[top - 1].first < cur->val) { ans[stack[top - 1].second] = cur->val; top--; } stack[top].first = cur->val; stack[top].second = idx; top++; cur = cur->next; } *returnSize = len; return ans; }
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
funcnextLargerNodes(head *ListNode) []int { var ans []int var stack [][]int cur := head idx := -1 for cur != nil { idx++ ans = append(ans, 0) forlen(stack) > 0 && stack[len(stack)-1][0] < cur.Val { top := stack[len(stack)-1] stack = stack[:len(stack)-1] ans[top[1]] = cur.Val } stack = append(stack, []int{cur.Val, idx}) cur = cur.Next } return ans }