C++反转链表

#include 

struct ListNode {
    int val;
    ListNode* next;
    ListNode(int x) : val(x), next(NULL) {}
};

ListNode* reverseList(ListNode* head) {
    ListNode* prev = NULL;
    ListNode* curr = head;
    ListNode* next = NULL;

    while (curr != NULL) {
        next = curr->next;
        curr->next = prev;
        prev = curr;
        curr = next;
    }

    return prev;
}

void printList(ListNode* head) {
    ListNode* curr = head;
    while (curr != NULL) {
        std::cout << curr->val << " ";
        curr = curr->next;
    }
    std::cout << std::endl;
}

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

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

    ListNode* reversedHead = reverseList(head);

    std::cout << "Reversed list: ";
    printList(reversedHead);

    return 0;
}

运行结果:

Original list: 1 2 3 4 5 
Reversed list: 5 4 3 2 1 

        在反转链表的代码中,我们使用三个指针(prev,curr和next),分别指向前一个节点、当前节点和下一个节点。我们通过逐个将当前节点的next指针指向前一个节点,完成链表的反转。最后,返回新的头节点prev。

你可能感兴趣的:(C++更多语法,计算机,/,人工智能,c++,链表,windows)