Reverse a singly linked list.

Best Solution:

class Solution(object):
    def reverse_list(self, head):
        rev = None
        while head:
            head.next,rev,head = rev,head,head.next
        return rev

Recursive solution

class Solution(object):
    def reverse_list(self, head):
        if head is None or head.next is None:
            return head

        reverse_node = self.reverse_list(head.next)
        head.next.next = head
        head.next = None
        return reverse_node

refer:

results matching ""

    No results matching ""