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;
    }
};

 

posted @ 2019-08-31 12:04  DH_HUSTer  阅读(18)  评论(0编辑  收藏  举报