92. Reverse Linked List II
反转链表总是要在至上画一画,有固定模式吗?
class Solution:
def reverseBetween(self, head: ListNode, left: int, right: int) -> ListNode:
dummy=ListNode(val=None,next=head)
curr1=curr2=dummy
for _ in range(right):
curr2=curr2.next
for _ in range(left-1):
curr1=curr1.next
for _ in range(right-left):
tmp=curr1.next
curr1.next=curr1.next.next
tmp.next=curr2.next
curr2.next=tmp
return dummy.next
206. Reverse Linked List
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if head is None:
return None
dummy = ListNode(val=None,next=head)
curr=dummy
while curr.next:
curr=curr.next
while dummy.next is not curr:
tmp=dummy.next
dummy.next=dummy.next.next
tmp.next=curr.next
curr.next=tmp
return dummy.next
有个极妙的题解,可惜可读性看来很差
class Solution:
def reverseList(self, head):
p, rev = head, None
while p:
rev, rev.next, p = p, rev, p.next
return rev