Post

단순 연결 리스트의 노드 순서를 뒤집는 함수

단순 연결 리스트의 노드 순서를 뒤집는 함수
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 단순 연결 리스트의 노드 순서 뒤집기 함수
void reverseList(Node*& head) {
    Node* prev = nullptr;
    Node* current = head;
    Node* next = nullptr;

    while (current != nullptr) {
        next = current->next;  // 현재 노드의 다음 노드를 저장
        current->next = prev;  // 현재 노드의 next를 이전 노드를 가리키도록 변경
        prev = current;        // prev를 현재 노드로 갱신
        current = next;        // current를 다음 노드로 갱신
    }
    head = prev;  // 마지막 노드가 새로운 head가 되도록 설정
}



img



전체 코드 참고

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>

// 연결 리스트의 노드 구조체 정의
struct Node {
    int data;
    Node* next;

    Node(int iValue) : data(iValue), next(nullptr) {}
};

// 연결 리스트 출력 함수
void printList(Node* head) {
    Node* temp = head;
    while (temp != nullptr) {
        std::cout << temp->data << " ";
        temp = temp->next;
    }
    std::cout << std::endl;
}

// 연결 리스트 뒤집기 함수
void reverseList(Node*& head) {
    Node* prev = nullptr;
    Node* current = head;
    Node* next = nullptr;

    while (current != nullptr) {

        next = current->next;  // 현재 노드의 다음 노드를 저장
        current->next = prev;  // 현재 노드의 next를 이전 노드를 가리키도록 변경
        prev = current;        // prev를 현재 노드로 갱신
        current = next;        // current를 다음 노드로 갱신

        std::cout << "prev: ";
        printList(prev);
    }
    head = prev;  // 마지막 노드가 새로운 head가 되도록 설정
}

int main() {
    // 연결 리스트 생성: 1 -> 2 -> 3 -> 4
    Node* head = new Node(1);
    head->next = new Node(2);
    head->next->next = new Node(3);
    head->next->next->next = new Node(4);

    std::cout << "Original List: ";
    printList(head);

    reverseList(head);  // 연결 리스트 뒤집기

    std::cout << "Reversed List: ";
    printList(head);  // 뒤집힌 리스트 출력

    return 0;
}
This post is licensed under CC BY 4.0 by the author.