from typing import List
class ListNode():
def __init__(self, val):
self.val = val
self.next = None
def __str__(self):
return str(self.val)
def createList(value_list: list) -> ListNode:
"""
Create Linked List based on list
:param value_list: list
:return: NodeList
"""
_len = len(value_list)
if _len == 0:
return None
if _len == 1:
return ListNode(value_list[0])
else:
root = ListNode(value_list[0])
tmp = root
for i in range(1, _len):
tmp.next = ListNode(value_list[i])
tmp = tmp.next
return root
def printList(head: ListNode):
"""
Print single node one by one in linked list
:param head: ListNode
:return: None
"""
p = head
while p != None:
print(p)
p = p.next
def listLength(head: ListNode) -> int:
"""
Get the length of linked list
:param head: ListNode
:return: int
"""
count = 0
p = head
while p != None:
count += 1
p = p.next
return count
class Solution:
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
if m == n: return head
if head == None: return head
if head.next == None: return head
dummy = ListNode(None)
dummy.next = head
pre_p = dummy
p = head
count = 1
while count <= n + 1:
if count < m:
p = p.next
pre_p = pre_p.next
elif count == m:
pre_start = pre_p
start = p
p = p.next
pre_p = pre_p.next
elif m < count <= n:
next_p = p.next
cur_p = p
p.next = pre_p
p = next_p
pre_p = cur_p
else:
pre_start.next = pre_p
start.next = p
count += 1
return dummy.next
Input = [[3,5], [1, 3, 5], [3, 5], [], [1], [1, 2, 3, 4, 5]]
Input1 = [1, 1, 1, 1, 1, 2]
Input2 = [1, 3, 2, 1, 1, 4]
Answer = [[3,5], [5, 3, 1], [5, 3], [], [1], [1, 4, 3, 2, 5]]
if __name__ == "__main__":
solution = Solution()
for i in range(len(Input)):
print("-"*50)
result = solution.reverseBetween(createList(Input[i]), Input1[i], Input2[i])
printList(result)
print(Answer[i])