leetcode:[206]反转链表

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 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:
    """
    1->2->3->4->None

    new_head
     |
    None<-4<-3<-2<-1

    new_head就是从None开始一直到原来链表的尾。
    在反转的时候先记录下一个节点,然后将当前节点反转,然后将更新新的表头,再遍历下一个节点
    """
    def reverseList(self, head: ListNode) -> ListNode:
        new_head = None
        while head:
            # 记录下一个节点,因为等下反转当前节点之后就会丢失下一个节点
            next_node = head.next
            # 反转当前节点。因为相对于head来说,new_head指向的是head的前一个节点
            head.next = new_head
            # 更新新的表头
            new_head = head
            # 将指针往后移动,这时就需要用到前面记录的节点
            head = next_node

        # 最后new_head就是反转后的表头
        return new_head

猜你喜欢

转载自blog.51cto.com/jayce1111/2381699