c++

如何在C++中逆转单链表

小樊
87
2024-07-16 20:14:52
栏目: 编程语言

以下是在C++中逆转单链表的示例代码:

#include <iostream>

struct Node {
    int data;
    Node* next;
    
    Node(int val) : data(val), next(nullptr) {}
};

Node* reverseLinkedList(Node* head) {
    Node* prev = nullptr;
    Node* current = head;
    Node* next = nullptr;
    
    while (current != nullptr) {
        next = current->next;
        current->next = prev;
        prev = current;
        current = next;
    }
    
    return prev;
}

void printLinkedList(Node* node) {
    while (node != nullptr) {
        std::cout << node->data << " ";
        node = node->next;
    }
    std::cout << std::endl;
}

int main() {
    Node* head = new Node(1);
    head->next = new Node(2);
    head->next->next = new Node(3);

    std::cout << "Original Linked List: ";
    printLinkedList(head);

    head = reverseLinkedList(head);

    std::cout << "Reversed Linked List: ";
    printLinkedList(head);

    return 0;
}

在这个示例中,我们定义了一个简单的Node结构来表示链表的节点,并实现了reverseLinkedList函数来反转链表。我们还实现了printLinkedList函数来打印链表的内容。在main函数中,我们创建了一个包含三个节点的链表,并打印出原始链表和反转后的链表。

0
看了该问题的人还看了