Skip to content

Instantly share code, notes, and snippets.

@Sl4vP0weR
Created May 9, 2022 08:20
Show Gist options
  • Save Sl4vP0weR/6a8be026319fd900e5c7b381860d4ad9 to your computer and use it in GitHub Desktop.
Save Sl4vP0weR/6a8be026319fd900e5c7b381860d4ad9 to your computer and use it in GitHub Desktop.
Extension for reversing the linked list.
/// <summary>
/// Creates new <see cref="LinkedList{T}"/> with reversed nodes.
/// </summary>
/// <typeparam name="T"></typeparam>
public static LinkedList<T> Reverse<T>(this LinkedList<T> originalList)
{
var reversedList = new LinkedList<T>();
var last = originalList.Last;
reversedList.AddFirst(last.Value);
while ((last = last.Previous) is not null)
reversedList.AddLast(last.Value);
return reversedList;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment