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
原文地址:https://www.cnblogs.com/yunxintryyoubest/p/13463660.html