给出创建一个链表并将其反转的完整代码
时间: 2024-02-22 08:56:22 浏览: 74
好的,下面是一个简单的 C++ 代码来创建链表并将其反转:
```c++
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
void printList(Node* node) {
while (node != NULL) {
cout << node->data << " ";
node = node->next;
}
cout << endl;
}
Node* reverseList(Node* head) {
Node* prev = NULL;
Node* curr = head;
Node* next = NULL;
while (curr != NULL) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
int main() {
Node* head = NULL;
Node* second = NULL;
Node* third = NULL;
head = new Node();
second = new Node();
third = new Node();
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = NULL;
cout << "Original List: ";
printList(head);
head = reverseList(head);
cout << "Reversed List: ";
printList(head);
return 0;
}
```
这个程序创建了一个简单的链表,其中包含三个节点。然后,`reverseList` 函数被调用,该函数接受链表的头节点作为参数,并返回反转后的链表的头节点。在主函数中,我们首先打印原始的链表,然后调用 `reverseList` 函数,再次打印反转后的链表。
阅读全文