LeetCode 206 Reverse Linked List--反转链表--迭代与递归解法--递归使用一个临时变量,迭代使用3个
发布日期:2022-03-18 18:19:28 浏览次数:1 分类:技术文章

本文共 1545 字,大约阅读时间需要 5 分钟。

此题链接:


Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULLOutput: 5->4->3->2->1->NULL

Follow up:

A linked list can be reversed either iteratively or recursively. Could you implement both?


这是一道经典的反转链表的题,有递归和迭代2种做法,其中使用递归可以只使用一个中间临时变量


Python迭代做法:

# Definition for singly-linked list.# class ListNode:#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution:    def reverseList(self, head: ListNode) -> ListNode:        prev = None        curr = head        while curr != None:            nextNode = curr.next            curr.next = prev            prev = curr            curr = nextNode        return prev

python递归做法:

# Definition for singly-linked list.# class ListNode:#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution:    def reverseList(self, head: ListNode) -> ListNode:        if(head == None or head.next == None):            return head        node = self.reverseList(head.next)        head.next.next = head        head.next = None        return node

C++迭代做法:

/** * 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) {
ListNode *prev = NULL; ListNode *curr = head; while (curr != NULL) {
ListNode *nextnode = curr->next; curr->next = prev; prev = curr; curr = nextnode; } return prev; }};

转载地址:https://zhang0peter.blog.csdn.net/article/details/88607026 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:记录在Ubuntu14.04上安装ryu中遇到的各种坑
下一篇:LeetCode 832 Flipping an Image

发表评论

最新留言

表示我来过!
[***.240.166.169]2024年03月30日 06时00分04秒