1、题目描述
反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
说明:
1 ≤ m ≤ n ≤ 链表长度。
示例:
输入: 1->2->3->4->5->NULL, m = 2, n = 4 输出: 1->4->3->2->5->NULL
2、题解
2.1、解法一
class Solution:
def reverseBetween(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""
# 反转
count = 0
node = head
stack = []
left = head
right = None
ret = []
while node:
count += 1
if count <m:
left = node
ret.append(node.val)
elif count >= m and count <=n:
stack.append(node)
elif count >n:
right = node
while len(stack):
tmp = stack.pop()
ret.append(tmp.val)
left.next = tmp
left = tmp
left.next = right
ret.append(right.val)
node = node.next
else:
while len(stack):
ret.append(stack.pop().val)
return ret