ในบทช่วยสอนนี้ เราจะเขียนโปรแกรมที่ค้นหาองค์ประกอบสูงสุดในรายการที่เชื่อมโยงที่กำหนด
องค์ประกอบสูงสุดเป็นองค์ประกอบที่มากกว่าองค์ประกอบโดยรอบ มาดูขั้นตอนการแก้ปัญหากัน
-
สร้างโหนดโครงสร้างสำหรับรายการที่เชื่อมโยง
-
สร้างรายการที่เชื่อมโยงด้วยข้อมูลจำลอง
-
ตรวจสอบกรณีพื้นฐานเช่นว่ารายการที่เชื่อมโยงว่างเปล่าหรือมีความยาว 1
-
เก็บองค์ประกอบแรกในตัวแปรที่เรียกว่าก่อนหน้า
-
วนซ้ำในรายการที่เชื่อมโยง
-
ตรวจสอบว่าองค์ประกอบปัจจุบันมากกว่าองค์ประกอบก่อนหน้าและองค์ประกอบถัดไปหรือไม่
-
ส่งคืนหากตรงตามเงื่อนไขข้างต้น
-
อัปเดตองค์ประกอบก่อนหน้า
-
-
พิมพ์ผลลัพธ์
ตัวอย่าง
มาดูโค้ดกันเลย
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node* next;
};
void insertNewNode(struct Node** head_ref, int new_data) {
struct Node* new_node = new Node;
new_node->data = new_data;
new_node->next = (*head_ref);
*head_ref = new_node;
}
int findPeakElement(struct Node* head) {
if (head == NULL) {
return -1;
}
if (head->next == NULL) {
return head->data;
}
int prev = head->data;
Node *current_node;
for (current_node = head->next; current_node->next != NULL; current_node = current_node->next) {
if (current_node->data > current_node->next->data && current_node->data > prev) {
return current_node->data;
}
prev = current_node->data;
}
if (current_node->data > prev) {
return current_node->data;
}
return -1;
}
int main() {
struct Node* head = NULL;
insertNewNode(&head, 7);
insertNewNode(&head, 4);
insertNewNode(&head, 5);
insertNewNode(&head, 2);
insertNewNode(&head, 3);
cout << findPeakElement(head) << endl;
return 0;
} ผลลัพธ์
หากคุณรันโค้ดด้านบน คุณจะได้ผลลัพธ์ดังต่อไปนี้
5
บทสรุป
หากคุณมีข้อสงสัยใดๆ ในบทแนะนำ โปรดระบุในส่วนความคิดเห็น