用 Python 编写反转链表的程序
pythonserver side programmingprogramming更新于 2026/2/3 6:36:17
假设我们有一个链表,我们必须反转它。因此,如果列表为 2 -> 4 -> 6 -> 8,则新的反转列表将是 8 -> 6 -> 4 -> 2。
为了解决这个问题,我们将遵循这种方法 −
- 定义一个以递归方式执行列表反转的过程,即solve(head, back)
- 如果 head 不存在,则返回 head
- temp := head.next
- head.next := back
- back := head
- 如果 temp 为空,则返回 head
- head := temp
- 返回 solve(head, back)
让我们看看下面的实现以便更好地理解 −
示例
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(object):
def reverseList(self, head):
return self.solve(head,None)
def solve(self, head, back):
if not head:
return head
temp= head.next
head.next = back
back = head
if not temp:
return head
head = temp
return self.solve(head,back)
list1 = make_list([5,8,9,6,4,7,8,1])
ob1 = Solution()
list2 = ob1.reverseList(list1)
print_list(list2)
输入
[5,8,9,6,4,7,8,1]
输出
[2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11, 14, 13,]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

