在c++中定义成员函数Inverse,将单链表中的元素逆置,并且输出逆置表中的数据
时间: 2024-10-08 09:17:29 浏览: 46
在C++中,为了定义一个成员函数`Inverse`来逆置单链表并输出逆置后的数据,你需要首先定义一个链表节点结构体和一个包含这个函数的类。下面是一个简单的示例:
```cpp
#include <iostream>
using namespace std;
// 定义链表节点结构体
struct Node {
int data;
Node* next;
};
class LinkedList {
private:
Node* head;
public:
// 构造函数、插入元素等方法省略
// 逆置链表并输出逆序数据
void Inverse() {
if (head == nullptr || head->next == nullptr) {
cout << "链表已逆置:" << head->data << endl;
return;
}
Node* prev = nullptr;
Node* current = head;
Node* next_temp;
// 使用三个指针,prev, current, 和 next_temp
// 逐个交换节点的位置
while (current != nullptr) {
next_temp = current->next;
current->next = prev;
prev = current;
current = next_temp;
}
// 更新链表头指向新的尾部
head = prev;
// 输出逆置后的数据
printList(head); // 假设有一个printList函数用于遍历并输出链表
}
// 辅助函数,打印链表内容
void printList(Node* node) {
while (node != nullptr) {
cout << node->data << " ";
node = node->next;
}
cout << endl;
}
};
int main() {
LinkedList list; // 创建链表实例
// 初始化链表...
list.Inverse(); // 调用逆置函数
// 输出逆置后的链表
return 0;
}
```
在这个例子中,`Inverse`函数首先检查链表是否为空或只有一个元素,然后通过三个指针(prev, current, 和 next_temp)进行链表的反转。最后,调用`printList`函数展示逆置后的链表。
阅读全文
相关推荐

















