题解 | #链表内指定区间反转#
链表内指定区间反转
http://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
注意
- m== 1 和n == 1是停止条件而非0
- 由于是翻转m和n之间的节点,所以需要记录n + 1个节点,翻转以后连起来
# class ListNode: # def __init__(self, x): # self.val = x # self.next = None # # # @param head ListNode类 # @param m int整型 # @param n int整型 # @return ListNode类 # class Solution: def reverseN(self, head, n): if n == 1: self.succ = head.next return head last = self.reverseN(head.next, n - 1) head.next.next = head head.next = self.succ return last def reverseBetween(self , head , m , n ): # write code here if m == 1: return self.reverseN(head, n) head.next = self.reverseBetween(head.next, m - 1, n - 1) return head