leetcode:[206]反转链表

Reverse a singly linked list.

10年积累的成都网站建设、成都网站制作经验,可以快速应对客户对网站的新想法和需求。提供各种问题对应的解决方案。让选择我们的客户得到更好、更有力的网络服务。我虽然不认识你,你也不认识我。但先网站设计后付款的网站建设流程,更有西藏免费网站建设让你可以放心的选择与我们合作。

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

网站标题:leetcode:[206]反转链表
转载来于:http://myzitong.com/article/poeohj.html