反轉相鄰連結串列單元

SmartDemo發表於2020-10-23
#include<iostream>

using namespace std;

struct Node {
    int val;
    Node* next;
    Node() :val(0), next(NULL) {}
    Node(int v) :val(v), next(NULL) {}
};
Node* reverseNeighbor(Node* head) {
    Node* dummy = new Node();
    dummy->next = head;//important
    Node* pre = dummy;
    Node* cur = head;
    Node* cnext = NULL;
    while (cur && cur->next) {
        cnext = cur->next;
        cur->next = cnext->next;
        cnext->next = cur;
        pre->next = cnext;
        pre = cur;
        cur = cur->next;
    }
    return dummy->next;
}
int main() {
    Node* head = new Node(1);
    head->next = new Node(2);
    head->next->next = new Node(3);
    head->next->next->next = new Node(4);
    Node* ans = reverseNeighbor(head);

    while (ans) {
        cout << ans->val << " ";
        ans = ans->next;
    }
    return 0;
}

 

相關文章