Node Class : For creating LinkList
public class Node<T> { private T nodeValue; private Node<T> nextNode; public Node() { this.nodeValue = default(T); this.nextNode = null; } public Node(T nodeValue) { this.nodeValue = nodeValue; this.nextNode = null; } /// <summary> /// Value of node /// </summary> public T NodeValue { get { return nodeValue; } set { this.nodeValue = value; } } /// <summary> /// The node this node links to /// </summary> public Node<T> NextNode { get { return this.nextNode; } set { this.nextNode = value; } } }
LinkList
class LinkList { public static void Test() { // Create a link list Node<int> a1 = new Node<int>(); a1.NodeValue = 10; Node<int> a2 = new Node<int>(); a2.NodeValue = 11; Node<int> a5 = new Node<int>(); a5.NodeValue = 12; Node<int> a3 = new Node<int>(); a3.NodeValue = 13; Node<int> a4 = new Node<int>(); a4.NodeValue = 14; a1.NextNode = a2; a2.NextNode = a3; a3.NextNode = a4; a4.NextNode = a5; a5.NextNode = null; //reverse the link list Console.WriteLine("----------------------------------------------------"); Console.WriteLine("Reverse List"); Reverse(ref a1); PrintLinkList(a1); Console.WriteLine("----------------------------------------------------"); } public static void Reverse(ref Node<int> head) { Node<int> first; Node<int> rest; if (head == null) return; first = head; rest = first.NextNode; if (rest == null) return; Reverse(ref rest); first.NextNode.NextNode = first; first.NextNode = null; head = rest; } public static void PrintLinkList(Node<int> head) { var temp = head; while (temp != null) { Console.Write(temp.NodeValue + "-->" ); temp = temp.NextNode; } Console.WriteLine(); } }
Filed under:
LinkList