返回列表
class Solution:def reverseBookList( self, head: Optional[ ListNode] ) -> List[ int] :li = [ ] while head:li.append( head.val) head = head.nextreturn li[ ::-1]
头插法,返回链表
class ListNode:def __init__( self, item) :self.val = itemself.next = Noneclass LinkedList:def rear_insert( self, li) :if not li:return Nonehead = ListNode( li[ 0 ] ) tail = head for val in li[ 1 :] :node = ListNode( val) tail.next = node tail = node return head def print( self, head ) :current = head while current:print( current.val, end = "->" ) current = current.nextprint( None) li = [ 2 , 6 , 8 , 9 ]
l = LinkedList( )
res = l.rear_insert( li) class Solution:def reverseBookList( self, head ) :li = [ ] while head:li.append( head.val) head = head.nextif not li:return Nonepre = ListNode( li[ 0 ] ) for i in li[ 1 :] :node = ListNode( i) node.next = prepre = node return prel.print( res)
sl = Solution( )
res_ = sl.reverseBookList( res)
l.print( res_)
尾插法,返回链表
class ListNode:def __init__( self, item) :self.val = itemself.next = Noneclass LinkedList:def rear_insert( self, li) :if not li:return Nonehead = ListNode( li[ 0 ] ) tail = head for val in li[ 1 :] :node = ListNode( val) tail.next = node tail = node return head def print( self, head ) :current = head while current:print( current.val, end = "->" ) current = current.nextprint( None) li = [ 2 , 6 , 8 , 9 ]
l = LinkedList( )
res = l.rear_insert( li) class Solution:def reverseBookList( self, head ) :cur = [ ] while head:cur.append( head.val) head = head.nextli = [ ] for _ in range( len( cur)) :li.append( cur.pop( )) if not li:return Nonepre = ListNode( li[ 0 ] ) tail = prefor i in li[ 1 :] :node = ListNode( i) tail.next = node tail = node return presl = Solution( )
l.print( res)
res_ = sl.reverseBookList( res)
l.print( res_)