[leetcode: Python]206.Reverse Linked List

题目:
反转一个单链表

方法一:性能58ms

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        #迭代
        new_head = None
        while head:
            p = head
            head = head.next
            p.next = new_head
            new_head = p
        return new_head

方法二:性能52ms

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        pre = None
        cur = None 
        while head: 
            cur = head 
            head = head.next
            cur.next = pre 
            pre = cur 
        return cur

你可能感兴趣的:(算法,python,leetcode)