假设我们有一个链表,我们必须扭转它。因此,如果列表类似于1→3→5→7,则新的反向列表将为7→5→3→1
为了解决这个问题,我们将遵循这种方法-
定义一个过程以递归的方式执行列表逆转,以解决(头,尾)
如果头部不存在,则返回头部
temp:= head.next
head.next:=返回
后=头
如果温度为空,则返回头
头=温度
返回解决(头,后)
让我们看下面的实现以更好地理解-
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): """ :type head: ListNode :rtype: ListNode """ return self.solve(head,None) def solve(self, head, back): if not head: return head temp= head.next #print(head.val) head.next = back back = head if not temp: return head head = temp return self.solve(head,back) list1 = make_list([1,3,5,7]) ob1 = Solution()list2 = ob1.reverseList(list1) print_list(list2)
list1 = [1,3,5,7]
输出结果
[7, 5, 3, 1, ]