How to reverse a singly linked list in-place in C#

1 Answer

0 votes
using System;

namespace ReverseLinkedListDemo
{
    // Node class for singly linked list
    public class ListNode
    {
        public int Value;        // data stored in the node
        public ListNode Next;    // reference to the next node

        public ListNode(int value)
        {
            Value = value;
            Next = null;
        }
    }

    class Program
    {
        // Reverse the linked list in-place
        public static ListNode ReverseList(ListNode head)
        {
            ListNode prev = null;        // will become the new head
            ListNode current = head;     // pointer to traverse the list
            ListNode nextNode = null;    // temporary pointer to store next node

            while (current != null) {
                nextNode = current.Next;   // save next node
                current.Next = prev;       // reverse the link
                prev = current;            // move prev forward
                current = nextNode;        // move current forward
            }

            return prev; // prev is the new head
        }

        // Print the linked list
        public static void PrintList(ListNode head)
        {
            ListNode temp = head;

            while (temp != null) {
                Console.Write(temp.Value);
                if (temp.Next != null)
                    Console.Write(" -> ");
                temp = temp.Next;
            }

            Console.WriteLine();
        }

        static void Main(string[] args)
        {
            // Build a sample list: 1 -> 2 -> 3 -> 4 -> 5
            ListNode head = new ListNode(1);
            head.Next = new ListNode(2);
            head.Next.Next = new ListNode(3);
            head.Next.Next.Next = new ListNode(4);
            head.Next.Next.Next.Next = new ListNode(5);

            Console.WriteLine("Original list:");
            PrintList(head);

            // Reverse the list
            head = ReverseList(head);

            Console.WriteLine("Reversed list:");
            PrintList(head);
        }
    }
}



/*
run:

Original list:
1 -> 2 -> 3 -> 4 -> 5
Reversed list:
5 -> 4 -> 3 -> 2 -> 1

*/

 



answered Jun 30 by avibootz
...