[Jian Zhi Offer] 24, reverse the linked list. Difficulty Level: Easy. The basic topic of linked list needs to be consolidated and strengthened.

1. Topic

Define a function that takes as input the head node of a linked list, reverses the linked list, and outputs the head node of the reversed list.

Example:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

2、code

For topic analysis, please refer to Jianzhi Offer 24. Reverse linked list (iteration/recursion, clear diagram)

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        # cur:current, pre:previous
        cur=head
        pre=None
        while cur:
            temp=cur.next
            cur.next=pre
            pre=cur
            cur=temp
        return pre

Guess you like

Origin blog.csdn.net/qq_43799400/article/details/131096156