n개의 요소가 있는 목록 L이 있습니다. 목록이 쌍으로 정렬되었는지 여부를 확인해야 합니다. 목록이 {8, 10, 18, 20, 5, 15}와 같다고 가정합니다. 이것은 (8, 10), (18, 20), (5, 15)가 정렬되어 쌍으로 정렬됩니다. 목록에 홀수개의 요소가 있는 경우 마지막 요소는 무시됩니다.
접근 방식은 너무 간단합니다. 숫자를 왼쪽에서 오른쪽으로 이동합니다. 두 개의 연속된 요소를 취해 정렬 여부를 확인하고, 한 쌍이 정렬되지 않으면 false를 반환하고, 정렬되지 않은 쌍이 없으면 true를 반환합니다.
예시
#include <iostream>
#include <cmath>
using namespace std;
class Node{
public:
int data;
Node *next;
};
void append(struct Node** start, int key) {
Node* new_node = new Node;
new_node->data = key;
new_node->next = (*start);
(*start) = new_node;
}
bool isPairwiseSorted(Node *start) {
bool flag = true;
struct Node* temp = start;
while (temp != NULL && temp->next != NULL) {
if (temp->data < temp->next->data) {
flag = false;
break;
}
temp = temp->next->next;
}
return flag;
}
int main() {
Node *start = NULL;
int arr[] = {8, 10, 18, 20, 5, 15};
int n = sizeof(arr)/sizeof(arr[0]);
for(int i = 0; i<n; i++){
append(&start, arr[i]);
}
if(isPairwiseSorted(start)){
cout << "This is pairwise sorted";
} else {
cout << "This is not pairwise sorted";
}
} 출력
This is pairwise sorted