写法1 王道书上的
从头结点开始,将链表中的每个节点取下来,逐个放在头结点后面,
维护三个指针 p,q,r ,p指向头结点,q为当前操作节点,r为下一个节点
将q指向p的下一个节点(也就是反转后的第一个节点),再将p的下一个节点指向q,然后qr向后平移
void reverse() {
Node *p,*q,*r;
p = head;
q = p->next;
p->next = nullptr;
while (q!=nullptr)
{
r = q->next;
q->next = p->next;
p->next = q;
q = r;
}
}
写法2 自己写的
同样维护三个指针,p指向当前操作的前一个节点,q指向当前要操作的节点,r指向下一个节点,
将q下一个节点指向q,然后pqr向后平移,最后将头结点指向反转后的第一个就行了,
这种写法更易理解,操作更加清晰。
void reverse2() {
Node* p, * q, * r;
p = head->next;
q = p->next;
p->next = nullptr;
while (q != nullptr)
{
r = q->next;
q->next = p;
p = q;
q = r;
}
head->next = p;
}
完整测试代码
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
Node(int val) : data(val), next(nullptr) {}
};
class LinkedList {
private:
Node* head;
public:
LinkedList() {
head = new Node(0); //头结点
}
void append(int val) {
Node* current = head;
while (current->next != nullptr) {
current = current->next;
}
current->next = new Node(val);
}
void display() {
Node* current = head;
current = current->next; // 跳过头结点
while (current != nullptr) {
cout << current->data << " ";
current = current->next;
}
}
void reverse() {
Node *p,*q,*r;
p = head;
q = p->next;
p->next = nullptr;
while (q!=nullptr)
{
r = q->next;
q->next = p->next;
p->next = q;
q = r;
}
}
void reverse2() {
Node* p, * q, * r;
p = head->next;
q = p->next;
p->next = nullptr;
while (q != nullptr)
{
r = q->next;
q->next = p;
p = q;
q = r;
}
head->next = p;
}
void clear() {
while (head != nullptr) {
Node* temp = head;
head = head->next;
delete temp;
}
}
~LinkedList() {
clear();
}
};
int main() {
LinkedList list;
list.append(1);
list.append(2);
list.append(3);
list.append(4);
list.append(5);
list.append(6);
list.reverse2();
list.display();
}