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