Reversing a linked list is common problem. OK there are several way of reversing a linked list. You will need 3 pointers. currentPointer, previousPointer, and nextPointer.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FiratAtagun.DataStrucutres.LinkedList
{
public class Node : IEquatable, IEquatable>, IComparable where T: IComparable
{
public T Value { set; get; }
public Node Next { set; get; }
public Node()
{
}
public Node(T value)
{
Value = value;
}
#region IEquatable Members
public bool Equals(T other)
{
return Value.Equals(other);
}
#endregion
#region IComparable Members
public int CompareTo(T other)
{
return Value.CompareTo(other);
}
#endregion
#region IEquatable> Members
public bool Equals(Node other)
{
return Value.Equals(other.Value);
}
#endregion
}
public enum OperationOptions
{
Default,
Iterative,
Recursive
}
public class MySinglyLinkedList : IEnumerable> where T: IComparable
{
public Node Head { set; get; }
public MySinglyLinkedList()
{
}
public MySinglyLinkedList(IEnumerable collection)
{
foreach (var element in collection)
{
Insert(element);
}
}
public Node Reverse()
{
Node currentPointer = Head;
Node nextPointer = null;
Node previousPointer = null;
while(currentPointer != null)
{
nextPointer = currentPointer.Next;
currentPointer.Next = previousPointer;
previousPointer = currentPointer;
currentPointer = nextPointer;
}
return previousPointer;
}
public void Insert(T data, OperationOptions operationOptions = OperationOptions.Iterative)
{
if(Head == null)
{
Head = new Node(data);
return;
}
if(operationOptions == OperationOptions.Default || operationOptions == OperationOptions.Iterative)
{
InsertIterative(data);
return;
}
InsertRecursive(data);
}
public void InsertIterative(T data)
{
InsertIterative(new Node(data));
}
public void InsertIterative(Node node)
{
var currentNode = Head;
while(currentNode.Next != null)
{
currentNode = currentNode.Next;
}
currentNode.Next = node;
}
public void InsertRecursive(T data)
{
var currentNode = Head;
InsertRecursive(new Node(data), currentNode);
}
public void InsertRecursive(Node node, Node insertAfterThis)
{
if(insertAfterThis.Next == null)
{
insertAfterThis.Next = node;
return;
}
InsertRecursive(node, insertAfterThis.Next);
}
#region IEnumerable> Members
public IEnumerator> GetEnumerator()
{
var currentNode = Head;
while (currentNode != null)
{
yield return currentNode;
currentNode = currentNode.Next;
}
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
}
Recent Comments