C++ 围绕给定值对链表进行分区并保持原始顺序
在本教程中给定一个链表,我们需要将所有小于 x 的数字放在列表的开头,其他数字放在后面。我们还需要保留它们与之前相同的顺序。例如
Input : 1->4->3->2->5->2->3, x = 3 Output: 1->2->2->3->3->4->5 Input : 1->4->2->10 x = 3 Output: 1->2->4->10 Input : 10->4->20->10->3 x = 3 Output: 3->10->4->20->10
要解决此问题,我们现在需要创建三个链表。当我们遇到一个小于 x 的数字时,我们将它插入第一个列表。现在对于等于 x 的值,我们将其放入第二个列表,对于更大的值,我们将其插入第三个列表。最后,我们将这些列表连接起来并打印最终列表。
查找解决方案的方法
在这种方法中,我们将维护三个列表,即 small、equal、large。现在我们保持它们的顺序并将这些列表连接到一个最终列表中,这是我们的答案。
示例
上述方法的 C++ 代码
#include<bits/stdc++.h>
using namespace std;
struct Node{ // structure for our node
int data;
struct Node* next;
};
// A utility function to create a new node
Node *newNode(int data){
struct Node* new_node = new Node;
new_node->data = data;
new_node->next = NULL;
return new_node;
}
struct Node *partition(struct Node *head, int x){
struct Node *smallhead = NULL, *smalllast = NULL; // we take two pointers for the list //so that it will help us in concatenation
struct Node *largelast = NULL, *largehead = NULL;
struct Node *equalhead = NULL, *equallast = NULL;
while (head != NULL){ // traversing through the original list
if (head->data == x){ // for equal to x
if (equalhead == NULL)
equalhead = equallast = head;
else{
equallast->next = head;
equallast = equallast->next;
}
}
else if (head->data < x){ // for smaller than x
if (smallhead == NULL)
smalllast = smallhead = head;
else{
smalllast->next = head;
smalllast = head;
}
}
else{ // for larger than x
if (largehead == NULL)
largelast = largehead = head;
else{
largelast->next = head;
largelast = head;
}
}
head = head->next;
}
if (largelast != NULL) // largelast will point to null as it is our last list
largelast->next = NULL;
/**********Concatenating the lists**********/
if (smallhead == NULL){
if (equalhead == NULL)
return largehead;
equallast->next = largehead;
return equalhead;
}
if (equalhead == NULL){
smalllast->next = largehead;
return smallhead;
}
smalllast->next = equalhead;
equallast->next = largehead;
return smallhead;
}
void printList(struct Node *head){ // function for printing our list
struct Node *temp = head;
while (temp != NULL){
printf("%d ", temp->data);
temp = temp->next;
}
}
int main(){
struct Node* head = newNode(10);
head->next = newNode(4);
head->next->next = newNode(5);
head->next->next->next = newNode(30);
head->next->next->next->next = newNode(2);
head->next->next->next->next->next = newNode(50);
int x = 3;
head = partition(head, x);
printList(head);
return 0;
}输出
2 10 4 5 30
上述代码的解释
在上面描述的方法中,我们将保留三个链表,其内容按顺序排列。这三个链表将分别包含小于、等于和大于 x 的元素。我们的任务现在简化了。我们需要连接这些列表,然后返回头部。
结论
在本教程中,我们解决了围绕给定值对链表进行分区并保持原始顺序的问题。我们还学习了此问题的 C++ 程序以及我们解决此问题的完整方法(常规方法)。我们可以用其他语言(如 C、Java、Python 和其他语言)编写相同的程序。我们希望您觉得本教程有所帮助。
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP