在Python中反转链表的内部节点的程序
假设我们有一个链表,还有两个值i和j,我们必须从第i个节点到第j个节点反转链表。最后返回更新后的列表。
因此,如果输入是[1,2,3,4,5,6,7,8,9],i = 2,j = 6,则输出将为[1, 2, 7, 6, 5, 4, 3, 8, 9,]。
为了解决这个问题,我们将遵循以下步骤:
- prev_head:创建一个带有与null相同值的链表节点,并指向节点
- prev:prev_head,curr:node
- 迭代从0到i的所有值,做:
- prev:curr,curr:curr的下一个
- rev_before:prev,rev_end:curr
- 迭代0到(j-i)的所有值,做:
- tmp:curr的下一个
- curr.next:prev
- prev,curr:curr,tmp
- rev_before.next:prev,rev_end.next:curr
- 返回prev_head的下一个
让我们看以下实现以更好地理解:
样例
class ListNode:
def __init__(self, data, next = None):
self.val = data
self.next = next
def make_list(elements):
head = ListNode(elements[0])
for element in elements[1:]:
ptr = head
while ptr.next:
ptr = ptr.next
ptr.next = ListNode(element)
return head
def print_list(head):
ptr = head
print('[', end = "")
while ptr:
print(ptr.val, end = ", ")
ptr = ptr.next
print(']')
class Solution:
def solve(self, node, i, j):
prev_head = ListNode(None, node)
prev, curr = prev_head, node
for _ in range(i):
prev, curr = curr, curr.next
rev_before, rev_end = prev, curr
for _ in range(j - i + 1):
tmp = curr.next
curr.next = prev
prev, curr = curr, tmp
rev_before.next, rev_end.next = prev, curr
return prev_head.next
ob = Solution()
head = make_list([1,2,3,4,5,6,7,8,9])
i = 2
j = 6
print_list(ob.solve(head, i, j))
输入
[1,2,3,4,5,6,7,8,9],2,6
输出
[1, 2, 7, 6, 5, 4, 3, 8, 9, ]