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==NULL||head->next==NULL) return head;
        ListNode* pre=NULL,*now=head,*q=head->next;
        while(q!=NULL){
            now->next=pre;
            pre=now;
            now=q;
            q=q->next;
        }
        now->next=pre;
        return now;
    }
};

解法二(递归):

/**
 * 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==NULL||head->next==NULL) return head;
        ListNode* res=reverseList(head->next);
        head->next->next=head;
        head->next=NULL;
        return res;
    }
};
原文地址:https://www.cnblogs.com/oneDongHua/p/14264012.html