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
Reverse A Singly Linked List - C#
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;
}
}





