使用 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

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

结论

如果您在本教程中有任何疑问,请在评论区中提出。

更新于: 2021年1月28日

106 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告