Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added Next Greater Node in Linked List #1722 #1754

Merged
merged 1 commit into from
Nov 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 95 additions & 0 deletions Linked_list/next-greater-node-in-linked-list/program.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
#include <stdio.h>
#include <stdlib.h>

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;
}
48 changes: 48 additions & 0 deletions Linked_list/next-greater-node-in-linked-list/readme.md
Original file line number Diff line number Diff line change
@@ -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.
Loading