用 C++ 查詢連結串列中的峰值元素
在本教程中,我們將編寫一個在給定連結串列中找到峰值元素的程式。
峰值元素是大於周圍元素的元素。讓我們看看解決該問題所需的步驟。
為連結串列建立一個節點結構。
用虛擬資料建立連結串列。
檢查基本情況,例如連結串列是否為空或長度是否為 1。
將第一個元素儲存在一個名為 previous 的變數中。
遍歷連結串列。
檢查當前元素是否大於前一個元素和後一個元素。
如果滿足上述條件,則返回。
更新前一個元素。
列印結果
示例
讓我們看看程式碼。
#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
結論
如果你對本教程有任何疑問,請在評論部分提出。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP