C++ program to find largest node in a Doubly linked list

In this article, we will learn how to find the largest node in a Doubly linked list in C++. A doubly linked list is a type of linked list where every node has three fields 1. data 2. link to previous node 3. link to next node if any present else NULL.

Examples

Input: 2 -> 3 -> 6 -> 8 -> 1 -> 4
Output: 8

Input: 1-> 3-> 5-> 7-> 9
Output: 9

Finding the largest node in a Doubly linked list in C++

1. Declare two pointers temp and max and initialize it to head pointer.

2. Now traverse the given list.

3. Compare if temp’s data is greater than the max’s data, if true update the max = temp.

4. Move to the next node i.e. temp = temp->next.

5. Finally, return data that stored the max pointer i.e. max->data.

#include <bits/stdc++.h>
using namespace std;
struct Node{
    int data;
    struct Node* prev;
    struct Node* next;
};
// function to insert the node at the beginning of the list
void push(Node** head, int data){
    Node* new_node = new Node;
    new_node->data = data;
    new_node->prev = NULL;
    new_node->next = (*head);
    if ((*head)!= NULL)
        (*head)->prev = new_node;
    (*head) = new_node;
}
// function to print the list
void print_list(Node* head){
    while (head != NULL){
        cout<<head->data<<" ";
        head = head->next;
    }
}
// function to find the largets node
int maxNode(Node** head){
    Node *max, *temp;
    temp = max = *head;
    while(temp != NULL){
        if (temp->data > max->data)
            max = temp;
        temp = temp->next;
    }
    return max->data;
}
int main(){
    Node* head = NULL;
    push(&head, 10);
    push(&head, 26);
    push(&head, 14);
    push(&head, 1);
    push(&head, 23);
    cout<<"The given Doubly Linked List is: ";
    print_list(head);
    cout<<"\n";
    cout<<"The largest node in the given doubly linked list is: "<<maxNode(&head);
    return 0;
}

Output

The given Doubly Linked List is: 23 1 14 26 10 
The largest node in the given doubly linked list is: 26

Also, read

Leave a Reply

Your email address will not be published.