如何使用C++分别实现顺序表和单链表的元素逆置?例如,初始列表为1, 2,3,4,5,6,逆置后变为6,5,4,3,2,1,要求算法空间复杂度为0(1)
时间: 2024-09-20 21:06:08 浏览: 36
在C++中,我们可以使用迭代的方式分别对顺序表(数组)和单链表进行元素逆置。
**顺序表(数组)逆置:**
```cpp
#include <iostream>
using namespace std;
void reverseArray(int arr[], int n) {
int start = 0;
int end = n - 1;
while (start < end) {
swap(arr[start], arr[end]);
start++;
end--;
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5, 6};
int size = sizeof(arr) / sizeof(arr[0]);
cout << "Original array: ";
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
reverseArray(arr, size);
cout << "\nReversed array: ";
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
return 0;
}
```
在这个例子中,我们不需要额外的空间,因为直接在原数组上交换元素。
**单链表逆置:**
```cpp
#include <iostream>
struct Node {
int data;
Node* next;
};
Node* reverseList(Node* head) {
Node* prev = nullptr;
Node* current = head;
Node* nextTemp;
while (current != nullptr) {
nextTemp = current->next;
current->next = prev;
prev = current;
current = nextTemp;
}
return prev;
}
// 辅助函数打印链表
void printList(Node* node) {
while (node != nullptr) {
cout << node->data << " -> ";
node = node->next;
}
cout << "nullptr" << endl;
}
int main() {
// 创建一个单链表示例:1->2->3->4->5->6
Node* head = new Node{1, nullptr};
head->next = new Node{2, nullptr};
head->next->next = new Node{3, nullptr};
head->next->next->next = new Node{4, nullptr};
head->next->next->next->next = new Node{5, nullptr};
head->next->next->next->next->next = new Node{6, nullptr};
cout << "Original linked list: ";
printList(head);
head = reverseList(head);
cout << "\nReversed linked list: ";
printList(head);
return 0;
}
```
这个链表逆置操作同样是在原链表上进行,所以空间复杂度为O(1)。
阅读全文