Hot Topics

NVDIA Solution
Technical Round
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
void reversePrint(struct node *head) {
if (head == NULL) {
return;
}
reversePrint(head->next);
printf("%d ", head->data);
}
This implementation uses a recursive approach to traverse the linked list and print its elements in reverse order. It first calls `reversePrint`
on the next node, and then it prints the data of the current node. This way, when the function returns, the elements are printed in the reverse order.
#include <pthread.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct LinkedList {
struct Node* head;
pthread_mutex_t lock;
};
void init(struct LinkedList* list) {
list->head = NULL;
pthread_mutex_init(&list->lock, NULL);
}
void insert(struct LinkedList* list, int data) {
struct Node* newNode = (struct Node*) malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
pthread_mutex_lock(&list->lock);
if (list->head == NULL) {
list->head = newNode;
} else {
struct Node* temp = list->head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
pthread_mutex_unlock(&list->lock);
}
In this implementation, a mutex (pthread_mutex_t
) is used to ensure exclusive access to the linked list structure while inserting new nodes. The pthread_mutex_lock
and pthread_mutex_unlock
functions are used to lock and unlock the mutex, respectively, while accessing the linked list. This ensures that multiple threads cannot modify the linked list simultaneously, avoiding race conditions.




Popular Category
Hot Topics
Go through our study material. Your Job is awaiting.