题目
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
leetcode:
https://leetcode.cn/problems/reverse-linked-list/
代码
迭代和递归两种方法(python)
import ast
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
# 迭代(双指针)
# def reverseList(self, head):
# """
# :type head: ListNode
# :rtype: ListNode
# """
# cur = head
# pre = None
# while cur:
# tmp = cur.next
# cur.next = pre
# pre = cur
# cur = tmp
# return pre
def reverseList(self, head: ListNode) -> ListNode:
def recur(cur, pre):
if not cur: return pre # 终止条件
res = recur(cur.next, cur) # 递归后继节点
cur.next = pre # 修改节点引用指向
return res # 返回反转链表的头节点
return recur(head, None) # 调用递归并返回
def list_to_linked_list(numbers):
# Convert a list of numbers to a linked list
if not numbers:
return None
nodes = [ListNode(x) for x in numbers]
for i in range(1, len(nodes)):
nodes[i - 1].next = nodes[i]
return nodes[0]
def linked_list_to_list(node):
# Convert a linked list to a list of numbers
result = []
while node:
result.append(node.val)
node = node.next
return result
# Get the input from the user
head_input = input("Please enter the list in the format [1,2,3,4,5]: ").strip('[]')
head = [int(i) for i in head_input.split(',') if i]
linked_list_head = list_to_linked_list(head)
solution = Solution()
reversed_linked_list_head = solution.reverseList(linked_list_head)
print(linked_list_to_list(reversed_linked_list_head)) # Output: [5, 4, 3, 2, 1]