leetcood學習筆記-206-反轉鏈表
阿新 • • 發佈:2019-03-19
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-反轉鏈表