反转链表(不改变节点指针方向)

#include <iostream>
#include <stack>
using namespace std;

struct Node{
    int data;
    Node *next;
    Node(int d) : data(d) {}
};

int label = 0;

//思路:设两个指针,left和right,首先将right走到头,交换left和right,然后每return一次,right自动向左一次,left手动向右走一次。
void Reverse(Node *&left, Node *right){
    if (!left || !right)
        return;

    Reverse(left, right->next);

    if (left == right || right->next == left){    //left == right适用奇数节点情况,right->next == left适用偶数节点情况
        label = 1;
        return;
    }
    if (label == 1)
        return;

    int tmp = left->data;
    left->data = right->data;
    right->data = tmp;
    left = left->next;
}

void Reverse(Node *start){
    if (!start)
        return;

    Reverse(start, start);
}

void PrintLinkedList(Node *start){
    while(start){
        cout<<start->data<<endl;
        start = start->next;
    }
}

int main()
{
    Node a(1);
    Node b(2);
    Node c(3);
    Node d(4);
    Node e(5);
    a.next = &b;
    b.next = &c;
    c.next = &d;
    d.next = &e;
    e.next = NULL;
    Reverse(&a);
    PrintLinkedList(&a);
    return 0;
}

EOF

原文地址:https://www.cnblogs.com/lihaozy/p/2839827.html