Skip to content

Instantly share code, notes, and snippets.

@cixuuz
Created October 23, 2017 14:42
Show Gist options
  • Save cixuuz/41917bf43ad494317a084f8d973a8ab1 to your computer and use it in GitHub Desktop.
Save cixuuz/41917bf43ad494317a084f8d973a8ab1 to your computer and use it in GitHub Desktop.
[92. Reverse Linked List II] #leetcode
class Solution:
def reverseBetween(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""
# corner case
if m == n:
return head
dummy = ListNode(0)
dummy.next = head
pre = dummy
# go to mth node
for i in range(m-1):
pre = pre.next
# reverse
reverse = None
cur = pre.next
for i in range(n-m+1):
nxt = cur.next
cur.next = reverse
reverse = cur
cur = nxt
pre.next.next = cur
pre.next = reverse
return dummy.next
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment