Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find the largest node in Doubly linked list in C++
In this problem, we are given a doubly linked list LL. Our task is to find the largest node in Doubly Linked List.
Let's take an example to understand the problem,
Input : linked-list = 5 -> 2 -> 9 -> 8 -> 1 -> 3 Output : 9
Solution Approach
A simple approach to solve the problem is by traversing the linked-list and if the data value of max is greater than maxVal's data. After traversing the linked-list, we will return the macVal nodes data.
Example
Program to illustrate the working of our solution
#include <iostream>
using namespace std;
struct Node{
int data;
struct Node* next;
struct Node* prev;
};
void push(struct Node** head_ref, int new_data){
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->prev = NULL;
new_node->next = (*head_ref);
if ((*head_ref) != NULL)
(*head_ref)->prev = new_node;
(*head_ref) = new_node;
}
int findLargestNodeInDLL(struct Node** head_ref){
struct Node *maxVal, *curr;
maxVal = curr = *head_ref;
while (curr != NULL){
if (curr->data > maxVal->data)
maxVal = curr;
curr = curr->next;
}
return maxVal->data;
}
int main(){
struct Node* head = NULL;
push(&head, 5);
push(&head, 2);
push(&head, 9);
push(&head, 1);
push(&head, 3);
cout<<"The largest node in doubly linked-list is "<<findLargestNodeInDLL(&head);
return 0;
}
Output
The largest node in doubly linked-list is 9
Advertisements