1. 程式人生 > >leetcood學習筆記-206-反轉鏈表

leetcood學習筆記-206-反轉鏈表

list 分享 nbsp 筆記 none app 技術分享 rev current

題目描述:

技術分享圖片

最佳解:

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        p,rev = head,None
        while p:
            rev,rev.next,p = p,rev,p.next
        return rev

解析:

技術分享圖片

技術分享圖片

方法二:遞歸

class Solution(object):
    
def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ return self.reverse(None,head) def reverse(self,current_node,next_node): if next_node is None: return current_node temp = next_node.next next_node.next
= current_node return self.reverse(next_node,temp)

方法三:棧

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        stack = [None]
        while head:
            stack.append(head)
            head 
= head.next p = stack.pop() head = p while head: head.next = stack.pop() head = head.next return p

leetcood學習筆記-206-反轉鏈表