ในปัญหานี้ เราได้รับ LL รายการที่เชื่อมโยงเป็นสองเท่า งานของเราคือ ค้นหาโหนดที่ใหญ่ที่สุดใน Doubly Linked List .
มาดูตัวอย่างเพื่อทำความเข้าใจปัญหากัน
Input : linked-list = 5 -> 2 -> 9 -> 8 -> 1 -> 3 Output : 9
แนวทางการแก้ปัญหา
แนวทางง่ายๆ ในการแก้ปัญหาคือผ่านรายการเชื่อมโยง และหากค่าข้อมูล max มากกว่าข้อมูลของ maxVal หลังจากผ่านรายการเชื่อมโยง เราจะส่งคืนข้อมูลโหนด macVal
ตัวอย่าง
โปรแกรมเพื่อแสดงการทำงานของโซลูชันของเรา
#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;
} ผลลัพธ์
The largest node in doubly linked-list is 9