The iron ML notebook
  • The iron data science notebook
  • ML & Data Science
    • Frequent Questions
      • Discriminative vs Generative models
      • Supervised vs Unsupervised learning
      • Batch vs Online Learning
      • Instance-based vs Model-based Learning
      • Bias-Variance Tradeoff
      • Probability vs Likelihood
      • Covariance vs Correlation Matrix
      • Precision vs Recall
      • How does a ROC curve work?
      • Ridge vs Lasso
      • Anomaly detection methods
      • How to deal with imbalanced datasets?
      • What is "Statistically Significant"?
      • Recommendation systems methods
    • Statistics
      • The basics
      • Distributions
      • Sampling
      • IQR
      • Z-score
      • F-statistic
      • Outliers
      • The bayesian basis
      • Statistic vs Parameter
      • Markov Monte Carlo Chain
    • ML Techniques
      • Pre-process
        • PCA
      • Loss functions
      • Regularization
      • Optimization
      • Metrics
        • Distance measures
      • Activation Functions
      • Selection functions
      • Feature Normalization
      • Cross-validation
      • Hyperparameter tuning
      • Ensemble methods
      • Hard negative mining
      • ML Serving
        • Quantization
        • Kernel Auto-Tuning
        • NVIDIA TensorRT vs ONNX Runtime
    • Machine Learning Algorithms
      • Supervised Learning
        • Support Vector Machines
        • Adaptative boosting
        • Gradient boosting
        • Regression algorithms
          • Linear Regression
          • Lasso regression
          • Multi Layer Perceptron
        • Classification algorithms
          • Perceptron
          • Logistic Regression
          • Multilayer Perceptron
          • kNN
          • Naive Bayes
          • Decision Trees
          • Random Forest
          • Gradient Boosted Trees
      • Unsupervised learning
        • Clustering
          • Clustering metrics
          • kMeans
          • Gaussian Mixture Model
          • Hierarchical clustering
          • DBSCAN
      • Cameras
        • Intrinsic and extrinsic parameters
    • Computer Vision
      • Object Detection
        • Two-Stage detectors
          • Traditional Detection Models
          • R-CNN
          • Fast R-CNN
          • Faster R-CNN
        • One-Stage detectors
          • YOLO
          • YOLO v2
          • YOLO v3
          • YOLOX
        • Techniques
          • NMS
          • ROI Pooling
        • Metrics
          • Objectness Score
          • Coco Metrics
          • IoU
      • MOT
        • SORT
        • Deep SORT
  • Related Topics
    • Intro
    • Python
      • Global Interpreter Lock (GIL)
      • Mutability
      • AsyncIO
    • SQL
    • Combinatorics
    • Data Engineering Questions
    • Distributed computation
      • About threads & processes
      • REST vs gRPC
  • Algorithms & data structures
    • Array
      • Online Stock Span
      • Two Sum
      • Best time to by and sell stock
      • Rank word combination
      • Largest subarray with zero sum
    • Binary
      • Sum of Two Integers
    • Tree
      • Maximum Depth of Binary Tree
      • Same Tree
      • Invert/Flip Binary Tree
      • Binary Tree Paths
      • Binary Tree Maximum Path Sum
    • Matrix
      • Set Matrix Zeroes
    • Linked List
      • Reverse Linked List
      • Detect Cycle
      • Merge Two Sorted Lists
      • Merge k Sorted Lists
    • String
      • Longest Substring Without Repeating Characters
      • Longest Repeating Character Replacement
      • Minimum Window Substring
    • Interval
    • Graph
    • Heap
    • Dynamic Programming
      • Fibonacci
      • Grid Traveler
      • Can Sum
      • How Sum
      • Best Sum
      • Can Construct
      • Count Construct
      • All Construct
      • Climbing Stairs
Powered by GitBook
On this page

Was this helpful?

  1. Algorithms & data structures
  2. Linked List

Reverse Linked List

PreviousLinked ListNextDetect Cycle

Last updated 3 years ago

Was this helpful?

# 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: Optional[ListNode]) -> Optional[ListNode]:
        return self.reverseListStack(head)
    
    def reverseListStack(self, head: Optional[ListNode]) -> Optional[ListNode]:
        """
        Time: O(N) + O(N) = O(N)
        Space: O(N)
        """
        
        if head is None:
            return head
        
        stack = []
        current = head
        while current != None:
            stack.append(current)
            current = current.next        
        
        head = current = stack.pop()  # set the top of the stack as the head
        while len(stack) > 0:  # iterate until stack is empty
            current.next = stack.pop()  # point next to top of the stack
            current = current.next  # move to next
        
        current.next = None
        return head
    
    def reverseListRecursiveWithFlags(
        self, 
        head: Optional[ListNode]
    ) -> Optional[ListNode]:
        """
        Time: O(N)
        Space: O(1) variables + O(N) stack calls = O(N)
        """
        
        if head is None:
            return None

        return self.util_reverseListRecursiveWithFlags(curr=head, prev=None)
    
    def util_reverseListRecursiveWithFlags(
        self, 
        curr: Optional[ListNode], 
        prev: Optional[ListNode]
    ) -> Optional[ListNode]:
        
        if curr.next is None:  # if end of recursion
            curr.next = prev  # set prev as next node of the last node
            
            return curr
        
        next_ = curr.next  # temporal store of next node
        curr.next = prev  # point next node to previous
        
        return self.util_reverseListRecursiveWithFlags(next_, curr)
    
    def reverseListRecursive(
        self, 
        head: Optional[ListNode]
    ) -> Optional[ListNode]:
        """
        Time: O(N)
        Space: O(1) variables + O(N) stack calls = O(N)
        """
        
        if head is None or head.next is None:
            return head

        rest = self.reverseListRecursive(head.next)
        
        head.next.next = head
        head.next = None    
        
        return rest
        
    def reverseListIterate(self, head: Optional[ListNode]) -> Optional[ListNode]:
        """
        Time: O(N)
        Space: O(1)
        """
        
        previous = None # set the previous as NULL
        current = head  # set the initial head as the current one
        while current != None:
            next_ = current.next  # save next node
            current.next = previous  # point to prev node or None (in 1st iter)
            previous = current  # move one position the previous flag
            current = next_  # set the saved next as the current
        
        return previous
https://leetcode.com/problems/reverse-linked-list
https://www.geeksforgeeks.org/reverse-a-linked-list/