检查链表是否成对地排好序的 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