From 9bccca635547631b5d504ed293de4e5d62a1fa97 Mon Sep 17 00:00:00 2001 From: Sanat Kumar Gupta <123228827+SKG24@users.noreply.github.com> Date: Fri, 8 Nov 2024 16:23:29 +0530 Subject: [PATCH] added Next Greater Node in Linked List #1722 Given the head of a linked list with `n` nodes, find the value of the next node that is strictly greater for each node in the list. If no such node exists, return `0` for that position. Return an integer array `answer` where `answer[i]` is the value of the next greater node of the `i`th node (1-indexed). --- .../program.c | 95 +++++++++++++++++++ .../readme.md | 48 ++++++++++ 2 files changed, 143 insertions(+) create mode 100644 Linked_list/next-greater-node-in-linked-list/program.c create mode 100644 Linked_list/next-greater-node-in-linked-list/readme.md diff --git a/Linked_list/next-greater-node-in-linked-list/program.c b/Linked_list/next-greater-node-in-linked-list/program.c new file mode 100644 index 00000000..18a1ab33 --- /dev/null +++ b/Linked_list/next-greater-node-in-linked-list/program.c @@ -0,0 +1,95 @@ +#include +#include + +struct ListNode { + int val; + struct ListNode* next; +}; + +// Function to create a new node +struct ListNode* createNode(int val) { + struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode)); + newNode->val = val; + newNode->next = NULL; + return newNode; +} + +// Function to add a new node at the end of the list +struct ListNode* addNode(struct ListNode* head, int val) { + if (head == NULL) return createNode(val); + struct ListNode* current = head; + while (current->next != NULL) { + current = current->next; + } + current->next = createNode(val); + return head; +} + +// Function to convert linked list to array +int* linkedListToArray(struct ListNode* head, int* size) { + int* values = (int*)malloc(10000 * sizeof(int)); // Allocate large array for simplicity + *size = 0; + while (head != NULL) { + values[(*size)++] = head->val; + head = head->next; + } + return values; +} + +// Function to find the next greater node values +int* nextLargerNodes(struct ListNode* head, int* returnSize) { + int size; + int* values = linkedListToArray(head, &size); // Convert linked list to array + *returnSize = size; + + int* result = (int*)calloc(size, sizeof(int)); // Initialize result array with 0 + int* stack = (int*)malloc(size * sizeof(int)); + int top = -1; // Stack pointer to store indices + + // Traverse the array to find the next greater element for each node + for (int i = 0; i < size; ++i) { + while (top >= 0 && values[i] > values[stack[top]]) { + result[stack[top]] = values[i]; + top--; + } + stack[++top] = i; + } + + // Clean up + free(values); + free(stack); + return result; +} + +// Function to print the result array +void printArray(int* array, int size) { + printf("Next greater nodes: "); + for (int i = 0; i < size; ++i) { + printf("%d ", array[i]); + } + printf("\n"); +} + +int main() { + struct ListNode* head = NULL; + head = addNode(head, 2); + head = addNode(head, 1); + head = addNode(head, 5); + + int resultSize; + int* result = nextLargerNodes(head, &resultSize); + + printArray(result, resultSize); + + // Free the linked list nodes + while (head != NULL) { + struct ListNode* temp = head; + head = head->next; + free(temp); + } + + // Free the result array + free(result); + + return 0; +} diff --git a/Linked_list/next-greater-node-in-linked-list/readme.md b/Linked_list/next-greater-node-in-linked-list/readme.md new file mode 100644 index 00000000..246fc7f2 --- /dev/null +++ b/Linked_list/next-greater-node-in-linked-list/readme.md @@ -0,0 +1,48 @@ +# Next Greater Node in Linked List + +## Problem Statement + +Given the head of a linked list with `n` nodes, find the value of the next node that is strictly greater for each node in the list. If no such node exists, return `0` for that position. + +Return an integer array `answer` where `answer[i]` is the value of the next greater node of the `i`th node (1-indexed). + +### Example + +**Input:** +head = `[2,1,5]` + +**Output:** +`[5,5,0]` + + +### Constraints +- The linked list can have up to `10^4` nodes. +- Each node contains a non-negative integer value. + +## Approach + +To solve this problem: +1. **Convert the Linked List to an Array**: Traverse the linked list and store each node’s value in an array. This allows easy access by index. +2. **Use a Stack to Track Indices of Nodes Waiting for a "Next Greater"**: + - Traverse the `values` array and maintain a stack of indices for which we haven't yet found a next greater value. + - For each element in `values`, check if it is greater than the elements at indices stored in the stack: + - If so, pop indices from the stack and set the `result` array for each index to this value. + - Push the current index to the stack if it doesn't have a greater element in the remainder of the array. +3. **Return the Result Array**: After processing all elements, the `result` array contains the next greater values or `0` for nodes that have no greater value ahead. + +### Complexity +- **Time Complexity**: `O(n)`, where `n` is the number of nodes, as each node is processed once. +- **Space Complexity**: `O(n)`, for storing values in the array and using the stack. + +## Code Explanation + +### Functions + +1. **createNode**: Creates a new linked list node. +2. **addNode**: Appends a node to the end of the linked list. +3. **linkedListToArray**: Converts the linked list to an array of values. +4. **nextLargerNodes**: The core function that computes the next greater node values. + - Initializes a result array `result` filled with `0`s. + - Uses a stack to keep track of indices where the next greater node has not been found. + - For each node value, checks if it’s greater than the values at indices stored in the stack. If so, it updates the result array for each index. +5. **printArray**: Prints the result array.