Introduction

Welcome to our exciting course, "Linked Lists, Stacks, and Queues in Python". Here, we aim to decode and comprehend the fundamentals and advanced concepts of Python's data structures. In this lesson, we delve deeper into applying two basic operations on Linked Lists – traversing through a list and calculating its length. These operations are akin to taking a walk down a street and counting the number of houses you have passed.

First, we define our goal and understand why we perform it. We then have a go at it using a straightforward approach before learning the efficient technique to accomplish it like a pro!

Problem 1: Reverse Linked List Traversal

While walking down a street, imagine you had to document each house but in reverse order. This presents a similar scenario, but instead, we are dealing with a linked list. The task is to traverse the list in reverse form and print all the elements.

Problem 1: Application

Traversing a list in a reverse manner is often encountered when you need to know the last state or the most recent actions in a scenario. For instance, in a browser history, the most recent web pages are usually at the top of your browsing history. In such a situation, you would need to traverse the list from the tail to the head.

Problem 1: Efficient Approach Explanation

To traverse a Linked List in reverse, we start from the tail node and move up to the previous node until we reach the head. However, because linked lists are generally singly linked lists and do not provide a direct way to access previous nodes, we must take a different approach. We can push all nodes onto a stack and then pop them out. This will give us the nodes in reverse order.

Problem 1: Solution Building

Unlike a book where you can quickly flip to the previous page, we have to navigate through the 'book' once (in other words, traverse the Linked List from head to tail), but 'mark' every page we visit (push every node on a stack). We then revisit the marked pages in reverse order (pop each node from the stack).

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal