Find a peak element in Linked List in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that finds the peak element in the given linked list.

The peak element is an element that is greater than the surrounding elements. Let's see the steps to solve the problem.

  • Create a struct node for the linked list.

  • Create the linked list with dummy data.

  • Check for the base cases like whether the linked list is empty or of length 1.

  • Store the first element in a variable called previous.

  • Iterate over the linked list.

    • Check whether the current element is greater than the previous element and the next element.

    • Return if the above condition satisfies.

    • Update the previous element.

  • Print the result

Example

Let's see the code.

 Live Demo

#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;
}

Output

If you execute the above code, then you will get the following result.

5

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

raja
Published on 01-Feb-2021 12:01:14
Advertisements