兩種方法解決leetcode206:Reverse Linked List

方法一:遞歸

其實在正序遞歸的時候已經確定了tail元素。回溯的時候,進行兩步

1. 讓head.next指向head

2. 讓head指向none

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head or not head.next:
            return head
        tail=self.reverseList(head.next)
        head.next.next=head
        head.next=None
        return tail

方法二:循環

每一次都讓head.next和head調換

class Solution:
    """
    @param head: n
    @return: The new head of reversed linked list.
    """
    def reverse(self, head):
        write your code here
        reverse=None
        while head!=None:
            temp=head.next
            head.next=reverse
            reverse=head
            head=temp
        return reverse

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章