struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};

方法1: 迭代

class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        ListNode *pre;
        ListNode *next;
        ListNode *curr;
        curr=pHead;
        pre=NULL;
        while(curr!=NULL)
        {
            next=curr->next;    //保存下一个
            curr->next=pre;    //指向前面一个
            pre=curr;          //保存前面一个
            curr=next;         //移动到下一个
        }
        return pre;
    }
};

方法2:递归

class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        if(pHead==NULL || pHead->next==NULL)
            return pHead;
        ListNode *new_head = ReverseList(pHead->next);
        pHead->next->next=pHead;
        pHead->next=NULL;
        return new_head;
    }
};

 

posted on 2021-05-30 16:32  ღ惟吾德馨ღ  阅读(55)  评论(0)    收藏  举报