美文网首页
leetcode 206. Reverse Linked Lis

leetcode 206. Reverse Linked Lis

作者: 咿呀咿呀呦__ | 来源:发表于2019-04-02 14:01 被阅读0次

Reverse a singly linked list.

Example:

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

Follow up:

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

class Solution:
    def reverseList(self, head):
        if head is None or head.next is None:
            return head
        
        prev, cur, nxt = None, head, head
        while cur is not None:
            nxt = cur.next
            cur.next = prev
            prev = cur
            cur = nxt
        return prev

主要就是找好prev, cur, nxt的位置,prev先设为None,这个也算一个小细节。

相关文章

网友评论

      本文标题:leetcode 206. Reverse Linked Lis

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