Linked Lists: Reversing and Length Calculation in C#

Introduction to the Lesson

Today's lesson will build upon our foundational understanding of linked lists by diving into practical implementation exercises using C#. These problems will sharpen your coding skills and prepare you for scenarios you might encounter in technical interviews.

Problem 1: Reverse Linked List Traversal

Picture a scenario in which you have a sequence of events stored in a linked list. Your task is to look back in time — essentially, to reverse the chronology of these events. In technical terms, this means traversing a singly linked list in reverse order while keeping its structure intact. This skill is critical, whether for reversing transaction logs or simply navigating through a playlist from end to start.

Problem 1: Problem Actualization

Consider a browser's back-button functionality, where the most recently visited pages must be revisited in reverse order. This operation mirrors our task of reverse traversal in a linked list, capturing the essence of a real-world application.

Problem 1: Naive Approach

One may consider creating a new linked list while iterating over the original list, inserting each element at the head of the new list. Although this approach might work, it is an overcomplicated approach that results in extra processing and memory usage that we can avoid.

Problem 1: Efficient Approach Explanation

A more sophisticated solution would use a stack. Using a stack, we ensure an orderly collection of the nodes' values as we navigate the list. Once the traversal is complete, we extract the values in reverse, thanks to the stack's Last-In-First-Out property.

Let's visualize it with a deck of cards: We pick each card from the top (the head of the linked list) and place it into a pile (the stack). When we finish, we pick up the cards from the pile now in reverse order.

Problem 1: Solution Building

Let's tackle it with C#:

using System;
using System.Collections.Generic;

class ListNode {
    public int Value;
    public ListNode Next;
    public ListNode(int value = 0, ListNode next = null) {
        Value = value;
        Next = next;
    }
}

class Program {
    static void ReversePrintLinkedList(ListNode head) {
        // Instantiate a stack to hold node values.
        Stack<int> stack = new Stack<int>();

        // Traverse the linked list and push node values to the stack.
        ListNode currentNode = head;
        while (currentNode != null) {
            stack.Push(currentNode.Value);
            currentNode = currentNode.Next;
        }

        // Pop from the stack to obtain elements in reversed order.
        while (stack.Count > 0) {
            Console.WriteLine(stack.Pop());
        }
    }
}

In this code, we create a Stack<int> to store integers. We then iterate through the linked list using a while loop. For each node visited, we push its value onto the stack. After traversing the entire list, we pop the values off the stack. This reversal is possible because stacks operate on a Last In, First Out (LIFO) principle, which means the last element added to the stack will be the first one removed, thus reversing the order of the elements.

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