CA 22 - Reverse a Linked List

 Reverse a Linked List

Given the head of a linked list, reverse the list and return the new head.

Examples

Input:

2

Output: 5 -> 4 -> 3 -> 2 -> 1

409842930

 CODE:

    Here to reverse the linked list all we have to do is change the interconnection, that is 1 -> 2 to 2 -> 1 in every step and then once we reach the last node which is 5 we will change the new head as 5. 

    To achieve this, we will use three pointers. Each to change the direction of connection, current, previous and next. Current will be at center, previous behind the current and next after the current. Now current -> next will be previous, then what will be the use of next pointer.

    Next pointer is used to traverse the linked list in original order. After changing the connection if current tries to move to it's next it we go back to 1 but we don't need that thus we make use of next.


class Solution:
    def reverse_linked_list(self,head):

    curr = head
    prev = None

    while curr:
        nextNode = curr.next
        curr.next = prev
        prev = curr
        curr = nextNode

    head = prev

Comments

Popular posts from this blog

CA 04 - Two Sum & Sorted Two Sum

CA 05 - Reverse the array

CA 21 - Basic Select SQL Queries