在 Python 中将链表反转的程序
假设我们有一个链表,我们需要反转它。因此,如果链表为 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,]
广告