码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode:[206]反转链表

时间:2019-04-20 00:22:39      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:val   output   node   NPU   example   开始   while   linked   efi   

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

leetcode:[206]反转链表

标签:val   output   node   NPU   example   开始   while   linked   efi   

原文地址:https://blog.51cto.com/jayce1111/2381699

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!