Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

หา Node ที่มีค่ามากที่สุดใน Doubly Linked List ใน C++

ในปัญหานี้ เราได้รับ Doubly Linked List งานคือหา node ที่มีค่า (data) มากที่สุด

ตัวอย่าง

Input: 5 ↔ 2 ↔ 9 ↔ 8 ↔ 1 ↔ 3 Output: 9

วิธีการแก้ปัญหา: Traversal แบบง่าย O(N)

  1. กำหนด maxNode = head
  2. Traverse ทุก node ผ่าน next pointer
  3. ถ้า current->data > maxNode->data → อัปเดต maxNode
  4. คืนค่า 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