以下是在C++中逆转单链表的示例代码:
#includestruct 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
函数中,我们创建了一个包含三个节点的链表,并打印出原始链表和反转后的链表。