Leetcode 206. 反转链表

题目要求:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

方法一:

 class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(!head) return head;
        ListNode* pre = nullptr;
        ListNode* cur = head;
        ListNode* tmp;
        while(cur) {
            tmp = cur->next;
            cur->next = pre;
            pre = cur;
            cur = tmp;
        }
        return pre;
    }
};

使用三个指针用来保存下一个节点,当前节点 和前一个节点。

方法二:

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(!head || !head->next) return head;
        ListNode* p = reverseList(head->next);
        head->next->next = head;
        head->next = nullptr;
        return p;
    }
};

递归用的很巧妙,对于链表的题目多了一种解题思路。不过要控制好边界情况。

posted @ 2019-10-28 00:15  Howardwang  阅读(129)  评论(0编辑  收藏  举报