问题描述
如何使用双指针反向链接列表?
我正在学习有关双指针的问题,并思考是否只能使用一个指针来反向链接列表。
解决方法
转换为使用指向左指针的指针作为读者的练习。在样式方面也有一些明显的缺点。
#include <iostream>
struct node {
int data;
node *next;
};
node *reverse(node *list) {
node *prev = NULL;
node *next;
while (list) {
next = list->next;
list->next = prev;
prev = list;
list = next;
}
return prev;
}
void show_list(node *list) {
while (list != NULL) {
std::cout << list->data << ",";
list = list->next;
}
}
int main() {
node *list = NULL;
for (int i=0; i<10; i++) {
node *n = new node;
n->next = list;
n->data = i;
list = n;
}
std::cout << "As built: ";
show_list(list);
list = reverse(list);
std::cout << "Reversed: ";
show_list(list);
return 0;
}
如果您决定修改作为参数接收的指针,则处理指针的引用可能要比指针的指针要容易得多。