程序在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:=节点
遍历从0到i的所有值,执行
上一页:= curr,curr:=下一个curr
rev_before:=上一步,rev_end:= curr
迭代从0到(j-i)的所有值,执行
tmp:=下一个
下一个curr:=上一页
上一页,当前:=当前,TMP
rev_before的下一个:=上一页,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, ]
以上是 程序在python中反向链接列表的内部节点 的全部内容, 来源链接: utcz.com/z/338006.html