点击查看代码
//Reversse a linked list
#include<iostream>
using namespace std;
struct node {
int data;
node* next;
};
node* A;
void reverse() {
node* next;//用于保存下一个·节点地址以便索引
node* current = A;//当前索引
node* prev = NULL;//保存上一个节点地址
while (current != NULL) {
next = current->next;//指向下一节点
current->next = prev;//当前节点尾巴指向上一节点
prev = current;//更新,指向当前节点
current = next;//索引指向下一节点
}
A = prev;//头指针指向末节点
}//头指针为空或只有一个节点时仍适用
void insert(int x) {
node* temp = new node;
temp->data = x;
temp->next = NULL;
if (A == NULL) {
A = temp;
}//头指针为空时要建立globle区与heap区的link才能通过头指针索引
else {
node* run = A;
while (run->next != NULL) {
run = run->next;
}
run->next = temp;
}//头指针不为空时用遍历指针索引
}
void print() {
node* run = A;
while (run != NULL) {
cout << run->data << " ";
run = run->next;
}
cout << endl;
}
int main() {
A = NULL;
insert(2);
insert(4);
insert(6);
insert(8);
print();
reverse();
print();
}