이 튜토리얼에서는 주어진 연결 리스트에서 피크 요소를 찾는 프로그램을 작성할 것입니다.
피크 요소는 주변 요소보다 큰 요소입니다. 문제를 해결하는 단계를 살펴보겠습니다.
-
연결 목록에 대한 구조체 노드를 만듭니다.
-
더미 데이터로 연결 리스트를 생성합니다.
-
연결 목록이 비어 있는지 또는 길이가 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
결론
튜토리얼에서 질문이 있는 경우 댓글 섹션에 언급하세요.