在本教程中,我们将编写一个程序,该程序在给定的链表中查找峰值元素。
峰值元素是大于周围元素的元素。让我们看看解决问题的步骤。
为链表创建一个struct节点。
用伪数据创建链接列表。
检查基本情况,例如链表是否为空或长度为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