Reverse Linked List

Question

Challenge Reverse it in-place and in one-pass

Thoughts

由于是单向list,所以只能从头开始,1->2变为2->1->null, 应该从1开始,并且维护两个pointer prev和curr, reverse当前两个点时用temp保存下一个node

Solution

"""
Definition of ListNode

class ListNode(object):

    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""
class Solution:
    """
    @param head: The first node of the linked list.
    @return: You should return the head of the reversed linked list. 
                  Reverse it in-place.
    """
    def reverse(self, head):
        # write your code here
        if not head:
            return head
        prev = None
        curr = head
        while curr:
            temp = curr.next
            curr.next = prev
            prev = curr
            curr = temp
        return prev