用 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

结论

如果你对本教程有任何疑问,请在评论部分提出。

更新于:01-Feb-2021

294 次浏览

开启你的 职业生涯

完成课程以获得认证

开始
广告
© . All rights reserved.