卖萌的弱渣

I am stupid, I am hungry.

Reverse Linked List

Reverse Linked List

Reverse a linked list

Example

For linked list 1->2->3, the reversed linked list is 3->2->1

Challenge

Reverse it in-place and in one-pass

Solution

  • Time: O(n)
(Reverse-Linked-List.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
"""
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 head == None or head.next == None:
            return head

        Dummy_node = ListNode(-1,None)
        Dummy_node.next = head
        front_node = Dummy_node.next
        end_node = front_node.next


        while end_node != None:
            next_node = end_node.next
            end_node.next = front_node
            front_node = end_node
            end_node = next_node

        head.next = None
        return front_node