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的值,我们把它放在第二个,对于更大的值,我们现在把它插入第三个。最后,我们连接列表并打印最终列表。
寻找解决方案的方法
在这种方法中,我们将维护三个列表,即小、相等、大。现在我们保持它们的顺序并将列表连接成最终列表,这就是我们的答案。
示例
上述方法的C++代码
#include<bits/stdc++.h>
using namespace std;
struct Node{ //我们节点的结构
int data;
struct Node* next;
};
//创建新节点的实用函数
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 //这样它就可以帮助我们进行串联
struct Node *largelast = NULL, *largehead = NULL;
struct Node *equalhead = NULL, *equallast = NULL;
while (head != NULL){ //遍历原始列表
if (head->data == x){ //对于等于x
if (equalhead == NULL)
equalhead = equallast = head;
else{
equallast->next = head;
equallast = equallast->next;
}
}
else if (head->data < x){ //对于小于x
if (smallhead == NULL)
smalllast = smallhead = head;
else{
smalllast->next = head;
smalllast = head;
}
}
else{ //对于大于x
if (largehead == NULL)
largelast = largehead = head;
else{
largelast->next = head;
largelast = head;
}
}
head = head->next;
}
if (largelast != NULL) //largelast将指向null因为它是我们的最后一个列表
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){ //打印我们的列表的功能
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++程序以及解决此问题的完整方法(Normal)。我们可以用其他语言编写相同的程序,例如C、java、python和其他语言。我们希望本教程对您有所帮助。