檢查連結串列是否成對地排好序的 C++ 程式碼
我們有一個包含 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP