Leetcode 206. 反转链表

迭代版本

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(!head) return head;
        ListNode* pre=head,*p=head->next,*t;
        pre->next=NULL;
        while(p){
            t=p->next;
            p->next=pre,pre=p,p=t;
        }
        return pre;
    }
};

递归版本

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(!head || !head->next) return head;
        ListNode* p=reverseList(head->next);
        head->next->next=head,head->next=NULL;
        return p;
    }
};

猜你喜欢

转载自blog.csdn.net/bendaai/article/details/81151772