Cho danh sách liên kết đôi (Doubly Linked List). Nhiệm vụ: tìm nút có giá trị lớn nhất.
Ví dụ minh họa
Input: 5 ↔ 2 ↔ 9 ↔ 8 ↔ 1 ↔ 3 Output: 9
Phương pháp giải
Duyệt danh sách, giữ con trỏ maxVal. So sánh data của mỗi nút với maxVal, cập nhật nếu lớn hơn.
Ví dụ chương trình
#include <iostream>
using namespace std;
struct Node{
int data;
Node* next;
Node* prev;
};
void push(Node** head_ref, int new_data){
Node* new_node = new Node();
new_node->data = new_data;
new_node->prev = NULL;
new_node->next = *head_ref;
if (*head_ref) (*head_ref)->prev = new_node;
*head_ref = new_node;
}
int findLargestNodeInDLL(Node** head_ref){
Node *maxVal = *head_ref, *curr = *head_ref;
while (curr){
if (curr->data > maxVal->data) maxVal = curr;
curr = curr->next;
}
return maxVal->data;
}
int main(){
Node* head = NULL;
push(&head, 5); push(&head, 2); push(&head, 9);
push(&head, 1); push(&head, 3);
cout << "Nút lớn nhất trong DLL: " << findLargestNodeInDLL(&head);
return 0;
}
Kết quả
Nút lớn nhất trong DLL: 9