美文网首页
leetcode--206--反转链表

leetcode--206--反转链表

作者: minningl | 来源:发表于2020-12-06 15:14 被阅读0次

题目:
反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

链接:https://leetcode-cn.com/problems/reverse-linked-list

思路:
1、尾递归。

Python代码:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):

    def reserse(self, guard, head):
        if (head==None):
            return guard
        temp = head.next
        head.next = guard
        return self.reserse(head, temp)

    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        return self.reserse(None, head)

C++代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:

    ListNode* reverse(ListNode* guard, ListNode* head){
        if (head==nullptr){
            return guard;
        }
        ListNode* temp = head->next;
        head->next = guard;
        return reverse(head, temp);
    }

    ListNode* reverseList(ListNode* head) {
        return reverse(nullptr, head);
    }
};

相关文章

  • leetcode--206--反转链表

    题目:反转一个单链表。 示例: 输入: 1->2->3->4->5->NULL输出: 5->4->3->2->1-...

  • leetcode--206--反转链表

    题目:反转一个单链表。 示例: 进阶:你可以迭代或递归地反转链表。你能否用两种方法解决这道题? 链接:https:...

  • Algorithm小白入门 -- 单链表

    单链表递归反转链表k个一组反转链表回文链表 1. 递归反转链表 单链表节点的结构如下: 1.1 递归反转整个单链表...

  • 链表反转

    循环反转链表 递归反转链表

  • 5个链表的常见操作

    链表 链表反转 LeetCode206:给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。 环路检...

  • JZ-015-反转链表

    反转链表 题目描述 输入一个链表,反转链表后,输出新链表的表头。题目链接: 反转链表[https://www.no...

  • 算法学习(链表相关问题)

    LeetCode 206 反转链表 LeetCode 92 反转链表II (练习) 完成,方法:在反转链表上改 L...

  • 实战高频leetcode题目

    1. 反转链表 : 反转链表是常见简单题目,定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点...

  • 【教3妹学算法】2道链表类题目

    题目1:反转链表 给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。 示例 1: 输入:head ...

  • leecode刷题(22)-- 反转链表

    leecode刷题(22)-- 反转链表 反转数组 反转一个单链表。 示例: 进阶:你可以迭代或递归地反转链表。你...

网友评论

      本文标题:leetcode--206--反转链表

      本文链接:https://www.haomeiwen.com/subject/dgmowktx.html