DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Aniruddha has posted 40 posts at DZone. View Full User Profile

Reverse A Singly Linked List - C#

11.09.2010
| 6684 views |
  • submit to reddit
        Reverse a Singly Linked List - C#

//Method to reverse a singly linked list
//The "Head" Parameter is the head of the original linked list which is passed to this method
//The method returns the head of the reversed linked list
public Node Reverse(Node Head)
        {
            Node reversedList = new Node(Head.Data);
            while (Head.Next != null)
            {
                Head = Head.Next;
                Node temp = reversedList;
                reversedList = new Node(Head.Data);
                reversedList.Next = temp;
            }
            return reversedList;
        }

// Sample Node Implementation
    public class Node
    {
        public int Data { get; set; }

        public Node Next { get; set; }

        public Node(int d)
        {
            this.Data = d;
        }

        public void AddNextNode(int d)
        {
            Node node = this;
            Node newNode = new Node(d);
            while (node.Next != null)
            {
                node = node.Next;
            }
            node.Next = newNode;
        }
    }