leetcode Reverse Linked List

来源:互联网 发布:软件导刊怎么样 编辑:程序博客网 时间:2024/06/06 09:45

   这道题题目的hint说,让我们尝试迭代和递归2种做法.

(1)迭代比较简单。注意最后头结点的next置为空,还有注意判断空,或者是只有一个节点的时候,这2种情况都直接返回root即可。

(2)主要是递归的做法。

函数功能是逆置一个以head为头的链表,那么可以先逆置head->next的,最后处理head。(可以有->next->next这种写法的)

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

0 0
原创粉丝点击