> 백엔드 개발 > C++ > 본문

연결된 목록이 주어지면 연결된 목록의 요소를 쌍으로 교환합니다.

WBOY
풀어 주다: 2023-08-26 10:33:10
앞으로
1278명이 탐색했습니다.

연결된 목록이 주어지면 연결된 목록의 요소를 쌍으로 교환합니다.

예를 들어 연결 목록에 있는 노드 쌍을 교환한 다음 인쇄해야 하는 문제를 해결하려면

Input : 1->2->3->4->5->6->NULL

Output : 2->1->4->3->6->5->NULL

Input : 1->2->3->4->5->NULL

Output : 2->1->4->3->5->NULL

Input : 1->NULL

Output : 1->NULL
로그인 후 복사

시간 복잡도가 O(N)인 솔루션을 얻는 방법에는 두 가지가 있습니다. 여기서 N은 연결된 목록은 크기를 제공하므로 이제 이 두 가지 방법을 살펴보겠습니다.

< h2>반복 방법

이 방법에서는 연결된 목록 요소를 반복하고 NULL에 도달할 때까지 쌍으로 교체합니다.

Example

#include <bits/stdc++.h>
using namespace std;
class Node { // node of our list
public:
    int data;
    Node* next;
};
void swapPairwise(Node* head){
    Node* temp = head;
    while (temp != NULL && temp->next != NULL) { // for pairwise swap we need to have 2 nodes hence we are checking
        swap(temp->data,
            temp->next->data); // swapping the data
        temp = temp->next->next; // going to the next pair
    }
}
void push(Node** head_ref, int new_data){ // function to push our data in list
    Node* new_node = new Node(); // creating new node
    new_node->data = new_data;
    new_node->next = (*head_ref); // head is pushed inwards
    (*head_ref) = new_node; // our new node becomes our head
}
void printList(Node* node){ // utility function to print the given linked list
    while (node != NULL) {
       cout << node->data << " ";
       node = node->next;
    }
}
int main(){
    Node* head = NULL;
    push(&head, 5);
    push(&head, 4);
    push(&head, 3);
    push(&head, 2);
    push(&head, 1);
    cout << "Linked list before\n";
    printList(head);
    swapPairwise(head);
    cout << "\nLinked list after\n";
    printList(head);
    return 0;
}
로그인 후 복사

Output

Linked list before
1 2 3 4 5
Linked list after
2 1 4 3 5
로그인 후 복사
로그인 후 복사

다음 방법에서는 동일한 수식을 사용하지만 재귀를 통해 반복합니다.

Recursive Method

이 방법에서는 재귀를 통해 동일한 논리를 구현합니다.

Example

#include <bits/stdc++.h>
using namespace std;
class Node { // node of our list
public:
    int data;
    Node* next;
};
void swapPairwise(struct Node* head){
    if (head != NULL && head->next != NULL) { // same condition as our iterative
        swap(head->data, head->next->data); // swapping data
        swapPairwise(head->next->next); // moving to the next pair
    }
    return; // else return
}
void push(Node** head_ref, int new_data){ // function to push our data in list
    Node* new_node = new Node(); // creating new node
    new_node->data = new_data;
    new_node->next = (*head_ref); // head is pushed inwards
    (*head_ref) = new_node; // our new node becomes our head
}
void printList(Node* node){ // utility function to print the given linked list
    while (node != NULL) {
        cout << node->data << " ";
        node = node->next;
    }
}
int main(){
    Node* head = NULL;
    push(&head, 5);
    push(&head, 4);
    push(&head, 3);
    push(&head, 2);
    push(&head, 1);
    cout << "Linked list before\n";
    printList(head);
    swapPairwise(head);
    cout << "\nLinked list after\n";
    printList(head);
    return 0;
}
로그인 후 복사

Output

Linked list before
1 2 3 4 5
Linked list after
2 1 4 3 5
로그인 후 복사
로그인 후 복사

위 코드 설명

이 방법에서는 연결된 목록을 쌍으로 순회합니다. 이제 쌍에 도달하면 데이터를 교환하고 다음 쌍으로 이동하며 이것이 두 가지 방법 모두에서 프로그램이 진행되는 방식입니다.

결론

이 튜토리얼에서는 재귀와 반복을 사용하여 주어진 연결 목록 요소의 쌍 교환을 해결했습니다. 우리는 또한 이 문제에 대한 C++ 프로그램과 이를 해결하기 위한 완전한 방법(일반)을 배웠습니다. C, Java, Python 및 기타 언어와 같은 다른 언어로 동일한 프로그램을 작성할 수 있습니다. 이 튜토리얼이 도움이 되었기를 바랍니다.

위 내용은 연결된 목록이 주어지면 연결된 목록의 요소를 쌍으로 교환합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:tutorialspoint.com
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!