Популярное

Музыка Кино и Анимация Автомобили Животные Спорт Путешествия Игры Юмор

Интересные видео

2025 Сериалы Трейлеры Новости Как сделать Видеоуроки Diy своими руками

Топ запросов

смотреть а4 schoolboy runaway турецкий сериал смотреть мультфильмы эдисон
dTub
Скачать

How To Reverse A Singly Linked List | The Ultimate Explanation (Iteratively & Recursively)

Автор: Back To Back SWE

Загружено: 2018-12-18

Просмотров: 169741

Описание:

Free 5-Day Mini-Course: https://backtobackswe.com
Try Our Full Platform: https://backtobackswe.com/pricing
📹 Intuitive Video Explanations
🏃 Run Code As You Learn
💾 Save Progress
❓New Unseen Questions
🔎 Get All Solutions


This is a classic interview problem for 1st and 2nd year interviews. I got this question in my interview for the Explore Microsoft Program.

Very simple. But we will still do this.

This is what I call a utility problem. Utility problems don't test your ability to think, they test your ability to do things such as traverse or manipulate data structures in often trivial (but not always) ways.

The brute force for this is to copy the linked list into a static structure like an array and then create a linked list from that...nah.

So the 2 ways we will really do it is to move the pointers around

Way 1 (Iterative):

For this approach we need to keep track of a prev and curr node. Why? This list is singly-linked so we can't get a node's predecessor, so during the traversal we must remember who came before the node we are at.

Before doing any of that we save the next node's address since if we move the node we are at's address, we would lose where to go next in the traversal.

Then finally we set the current node to the next node that we saved at the start of the iteration.

Complexities:

Time: O(n)
Space: O(1)

Way 2 (Recursive):

This is "top down" recursion, we start at the top and drill down. Then when we reach the bottom (the base case) we will come back upwards with the answer.

The recursive code will drill down in recursive calls until we get to the base case.

The base case gets triggered when the current node has no next, this means we are at the list's end, in that case we just return the node passed into the call.

Then the node before the last node has itself and the last node to work with.

We do some pointer movement.

Last node points to curr.

curr pointer to null since we don't know if this is the first node in the list.

first node will end up the last node in the list.

Then we return the head of the new linked list on the way back upwards.

The we repeat, what we get from the recursive call is a reversed list, we append our node to that list, and then return back upwards with an even longer reversed list.

In the top call we say:

"Reverse the rest of the list"
"Reverse the rest of the list"
"Reverse the rest of the list"
I'm the last node "Here I am 2nd to last node"
"processing"
3rd to last gets a reversed list, append
4th to last gets a reversed list, append
......and so on

Complexities:

Time: O(n)
Space: O(n)

Call stack space used.

++++++++++++++++++++++++++++++++++++++++++++++++++

HackerRank:    / @hackerrankofficial  

Tuschar Roy:    / tusharroy2525  

GeeksForGeeks:    / @geeksforgeeksvideos  

Jarvis Johnson:    / vsympathyv  

Success In Tech:    / @successintech  

How To Reverse A Singly Linked List | The Ultimate Explanation (Iteratively & Recursively)

Поделиться в:

Доступные форматы для скачивания:

Скачать видео mp4

  • Информация по загрузке:

Скачать аудио mp3

Похожие видео

Клонирование связанного списка (со случайными указателями) — решение с линейным пространством и с...

Клонирование связанного списка (со случайными указателями) — решение с линейным пространством и с...

Reverse Linked List - LeetCode  206 - Python (Iterative and Recursive)

Reverse Linked List - LeetCode 206 - Python (Iterative and Recursive)

Binary Tree Bootcamp: Full, Complete, & Perfect Trees. Preorder, Inorder, & Postorder Traversal.

Binary Tree Bootcamp: Full, Complete, & Perfect Trees. Preorder, Inorder, & Postorder Traversal.

Reverse a linked list using recursion

Reverse a linked list using recursion

The Recursive Staircase - Top Down & Bottom Up Dynamic Programming (

The Recursive Staircase - Top Down & Bottom Up Dynamic Programming ("Climbing Stairs" on LeetCode)

LeetCode - Reverse Linked List Solution

LeetCode - Reverse Linked List Solution

Строка кода, которая обрушила Интернет

Строка кода, которая обрушила Интернет

Minimum Window Substring: Utilizing Two Pointers & Tracking Character Mappings With A Hashtable

Minimum Window Substring: Utilizing Two Pointers & Tracking Character Mappings With A Hashtable

LLM и GPT - как работают большие языковые модели? Визуальное введение в трансформеры

LLM и GPT - как работают большие языковые модели? Визуальное введение в трансформеры

The 0/1 Knapsack Problem (Demystifying Dynamic Programming)

The 0/1 Knapsack Problem (Demystifying Dynamic Programming)

Reverse Linked List - Iterative AND Recursive - Leetcode 206 - Python

Reverse Linked List - Iterative AND Recursive - Leetcode 206 - Python

Алгоритмы и структуры данных за 15 минут! Вместо 4 лет универа

Алгоритмы и структуры данных за 15 минут! Вместо 4 лет универа

Reverse Linked List Recursively

Reverse Linked List Recursively

Reverse Linked List | EP 10

Reverse Linked List | EP 10

ЛУЧШАЯ БЕСПЛАТНАЯ НЕЙРОСЕТЬ Google, которой нет аналогов

ЛУЧШАЯ БЕСПЛАТНАЯ НЕЙРОСЕТЬ Google, которой нет аналогов

6. Recursion and Dictionaries

6. Recursion and Dictionaries

Куда исчезает ёмкость MLCC? Эффект DC-Bias и старение керамики X7R

Куда исчезает ёмкость MLCC? Эффект DC-Bias и старение керамики X7R

Алгоритм быстрой сортировки: выбор опорного элемента, разбиение и рекурсия

Алгоритм быстрой сортировки: выбор опорного элемента, разбиение и рекурсия

Наименьший общий предок между двумя узлами двоичного дерева (рекурсивный подход)

Наименьший общий предок между двумя узлами двоичного дерева (рекурсивный подход)

Introduction to Linked Lists (Data Structures & Algorithms #5)

Introduction to Linked Lists (Data Structures & Algorithms #5)

© 2025 dtub. Все права защищены.



  • Контакты
  • О нас
  • Политика конфиденциальности



Контакты для правообладателей: [email protected]