206.Reverse Linked List

  • 迭代:
/**
 * 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* cur = head;
        ListNode* prev = NULL;
        while(cur != NULL){
            ListNode* next = cur->next;
            cur->next = prev;
            prev = cur;
            cur = next;
        }
        return prev;
    }

    
};
  • 递归
/**
 * 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;
        return getreverse(NULL,head);
    }
    
    ListNode* getreverse(ListNode* prev,ListNode* cur){        //每一次递归就相当于将cur和prev向前移动
        if(cur == NULL){
            return prev;
        }
        ListNode* next = cur->next;
        cur->next = prev;
        return getreverse(cur,next);
    }
    
};
posted @ 2017-07-13 13:50  UniMilky  阅读(93)  评论(0编辑  收藏  举报