From 56d5a8dd5dffecf922eac1682235153291ea9d9d Mon Sep 17 00:00:00 2001 From: Danish Faisal <43044452+danish-faisal@users.noreply.github.com> Date: Fri, 8 Oct 2021 22:53:00 +0530 Subject: [PATCH] Solution to Reversing a Linked List --- Leetcode/Python/reverse-a-linked-list.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Leetcode/Python/reverse-a-linked-list.py diff --git a/Leetcode/Python/reverse-a-linked-list.py b/Leetcode/Python/reverse-a-linked-list.py new file mode 100644 index 00000000..ea95271b --- /dev/null +++ b/Leetcode/Python/reverse-a-linked-list.py @@ -0,0 +1,22 @@ +# https://leetcode.com/problems/reverse-linked-list/ + +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next + +class Solution: + def reverseList(self, head: ListNode) -> ListNode: + curr = head + prev = None + while curr is not None: + # storing the next node + nextTemp = curr.next + # making the current node point to previous node + curr.next = prev + # for next iteration -> update previous node to current node & current node to next node + prev = curr + curr = nextTemp + + return prev