在C ++程序中,将给定的链表分成大小比为p:q的两个列表
在本教程中,我们将编写一个程序,将给定的链表分为ap:q比
这是一个简单的程序。让我们看看解决问题的步骤。
为链接列表节点创建一个结构。
用伪数据初始化链表。
初始化p:q比。
查找链接列表的长度。
如果链接列表的长度小于p+q,则无法将链接划分为ap: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;
//查找链表的长度
while (temp != NULL) {
n += 1;
temp = temp->next;
}
//检查我们是否可以划分链接列表
if (p + q > n) {
cout << "Can't divide Linked list" << endl;
}
else {
temp = head;
while (p > 1) {
temp = temp->next;
p -= 1;
}
//拆分后的第二个头节点
Node *head_two = temp->next;
temp->next = NULL;
//打印链表
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
结论
热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志