使用 C++ 程式將給定的連結串列分成 p:q 比例的兩個連結串列


在本教程中,我們將編寫一個程式,將給定的連結串列分成 p:q 比例。

這是一個簡單的程式。讓我們看看解決問題的步驟。

  • 為連結串列節點建立一個結構體。

  • 使用虛擬資料初始化連結串列。

  • 初始化 p:q 比例。

  • 查詢連結串列的長度。

  • 如果連結串列的長度小於 p + q,則無法將連結串列分成 p:q 比例。

  • 否則,迭代連結串列直到 p。

  • 在 p 次迭代之後,移除連結併為第二個連結串列建立一個新的頭節點。

  • 現在,列印連結串列的兩個部分。

示例

讓我們看看程式碼。

 線上演示

#include<bits/stdc++.h>
using namespace std;
struct Node {
   int data;
   Node *next;
   Node(int data) {
      this->data = data;
      this->next = NULL;
   }
};
void printLinkedList(Node* head) {
   Node *temp = head;
   while (temp) {
      cout << temp->data << " -> ";
      temp = temp->next;
   }
   cout << "NULL" << endl;
}
void splitLinkedList(Node *head, int p, int q) {
   int n = 0;
   Node *temp = head;
   // finding the length of the linked list
   while (temp != NULL) {
      n += 1;
      temp = temp->next;
   }
   // checking wether we can divide the linked list or not
   if (p + q > n) {
      cout << "Can't divide Linked list" << endl;
   }
   else {
      temp = head;
      while (p > 1) {
         temp = temp->next;
         p -= 1;
      }
      // second head node after splitting
      Node *head_two = temp->next;
      temp->next = NULL;
      // printing linked lists
      printLinkedList(head);
      printLinkedList(head_two);
   }
}
int main() {
   Node* head = new Node(1);
   head->next = new Node(2);
   head->next->next = new Node(3);
   head->next->next->next = new Node(4);
   head->next->next->next->next = new Node(5);
   head->next->next->next->next->next = new Node(6);
   int p = 2, q = 4;
   splitLinkedList(head, p, q);
}

輸出

如果執行以上程式碼,則將獲得以下結果。

1 -> 2 -> NULL
3 -> 4 -> 5 -> 6 -> NULL

結論

如果您在本教程中有任何疑問,請在評論區中提出。

更新於: 2021年1月28日

106 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.