ในปัญหานี้ เราได้รับ Doubly Linked List งานคือหา node ที่มีค่า (data) มากที่สุด
ตัวอย่าง
Input: 5 ↔ 2 ↔ 9 ↔ 8 ↔ 1 ↔ 3 Output: 9
วิธีการแก้ปัญหา: Traversal แบบง่าย O(N)
- กำหนด maxNode = head
- Traverse ทุก node ผ่าน next pointer
- ถ้า current->data > maxNode->data → อัปเดต maxNode
- คืนค่า maxNode->data
ตัวอย่างโค้ด
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
Node* prev;
};
void push(Node** head, int data) {
Node* newNode = new Node();
newNode->data = data;
newNode->prev = NULL;
newNode->next = *head;
if (*head) (*head)->prev = newNode;
*head = newNode;
}
int findLargestNode(Node* head) {
Node* maxNode = head;
Node* curr = head;
while (curr) {
if (curr->data > maxNode->data) maxNode = curr;
curr = curr->next;
}
return maxNode->data;
}
int main() {
Node* head = NULL;
push(&head, 5); push(&head, 2); push(&head, 9);
push(&head, 1); push(&head, 3);
cout << "Largest node: " << findLargestNode(head);
return 0;
}
ผลลัพธ์
Largest node in doubly linked-list is 9