이 튜토리얼에서 연결 리스트가 주어지면 리스트의 시작 부분에서 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++ 프로그램과 이 문제를 해결하는 완전한 접근 방식(Normal)을 배웠습니다. C, Java, python 및 기타 언어와 같은 다른 언어로 동일한 프로그램을 작성할 수 있습니다. 이 튜토리얼이 도움이 되기를 바랍니다.