檢查連結串列是否成對地排好序的 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

更新日期:2019-10-22

131 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告