剑指offer面试题24:leetcode206 反转链表 Python3实现

【原题连接】
反转一个单链表。

思路:三个指针 pre cur nxt
示例:

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

# 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:
        pre = None
        cur = head
        while cur:
            nxt = cur.next #防止链表断裂
            cur.next = pre
            pre = cur
            cur = nxt
        
        return pre

你可能感兴趣的:(leetcode刷题,剑指offer)