-
Notifications
You must be signed in to change notification settings - Fork 0
/
1019 Next Greater Node in Linked List.c
95 lines (83 loc) · 2.2 KB
/
1019 Next Greater Node in Linked List.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
#define MAX_NO_OF_NODES 10000
typedef struct stack
{
int data_arr[MAX_NO_OF_NODES];
int top;
}Stack;
int isStackFull(Stack * next_larger_node_stack)
{
if(next_larger_node_stack->top == (MAX_NO_OF_NODES-1))
{
return 1;
}
else
return 0;
}
void enqueue( Stack * next_larger_node_stack, int data)
{
if(isStackFull(next_larger_node_stack))
{
return;
}
next_larger_node_stack->data_arr[++(next_larger_node_stack->top)] = data;
}
int count_and_items_push(struct ListNode * head, Stack * next_larger_node_stack)
{
struct ListNode * trav_ptr = head;
int count = 0;
while(trav_ptr!=NULL)
{
enqueue(next_larger_node_stack, trav_ptr->val);
count++;
trav_ptr = trav_ptr->next;
}
return count;
}
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* nextLargerNodes(struct ListNode* head, int* returnSize)
{
Stack next_larger_node_stack;
next_larger_node_stack.top = -1;
//Count number of nodes and push item in the stack
int no_of_nodes = count_and_items_push(head, &next_larger_node_stack);
*returnSize = no_of_nodes;
int * ret_arr = (int *)malloc(sizeof(int)*no_of_nodes);
int ret_arr_index = 0;
struct ListNode * trav_ptr = head;
int stack_index = 0;
while(trav_ptr!=NULL)
{
int i=0;
bool next_larger_node_found = false;
for(i=stack_index+1; i<=next_larger_node_stack.top; i++)
{
if(i > next_larger_node_stack.top)
{
next_larger_node_found = false;
break;
}
if(next_larger_node_stack.data_arr[i] > trav_ptr->val)
{
next_larger_node_found = true;
ret_arr[ret_arr_index++] = next_larger_node_stack.data_arr[i];
break;
}
}
if(!next_larger_node_found)
{
ret_arr[ret_arr_index++] = 0;
}
stack_index++;
trav_ptr = trav_ptr->next;
}
return ret_arr;
}