35. 翻转链表

35. 翻转链表

中文English

翻转一个链表

样例

样例 1:

输入: 1->2->3->null
输出: 3->2->1->null

样例 2:

输入: 1->2->3->4->null
输出: 4->3->2->1->null

挑战

在原地一次翻转完成

 
 
输入测试数据 (每行一个参数)如何理解测试数据?

 

"""
Definition of ListNode

class ListNode(object):

    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""

class Solution:
    """
    @param head: n
    @return: The new head of reversed linked list.
    """
    def reverse(self, head):
        # write your code here
        
        pre_Node = None

        while head:
            next_Node = head.next
            head.next = pre_Node
            pre_Node = head
            head = next_Node 
        
        return pre_Node

 

posted @ 2020-08-09 17:39  风不再来  阅读(132)  评论(0编辑  收藏  举报