链表反转

#include "iostream"
using namespace std;
struct node {
    int val;
    node *next;
    node(int v): val(v), next(NULL){}
};
node* reverse(node* n) {
    node* head = n;
    node* tmp1 = n;
    node* tmp2 = n->next;
    node* tmp3 = n->next->next;
    while (tmp3 != NULL) {
        tmp2->next = tmp1;
        tmp1 = tmp2;
        tmp2 = tmp3;
        tmp3 = tmp3->next;
    }
    tmp2->next = tmp1;
    head->next = tmp3;
    return tmp2;
}
int main() {
    node *root;
    root = new node(1);
    root->next = new node(2);    
    root->next->next = new node(3);
    root->next->next->next = new node(4);
    root = reverse(root);
    while(root != NULL) {
        printf("%d ", root->val);
        root = root->next;
    }
    return 0;
}
posted @ 2020-03-23 13:51  SteveYu  阅读(127)  评论(0编辑  收藏  举报