linked list reversal recursive
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Node head = null;
LinkedList.Append(ref head, 1);
LinkedList.Append(ref head, 2);
LinkedList.Append(ref head, 3);
LinkedList.Append(ref head, 4);
Node res = LinkedList.ReverseRecursive(head, null);
LinkedList.Print(res);
Console.Read();
}
public static class LinkedList
{
public static void Append(ref Node head, int data)
{
if(head != null)
{
Node current = head;
while(current.Next != null)
{
current = current.Next;
}
current.Next = new Node();
current.Next.Data = data;
}
else
{
head = new Node();
head.Data = data;
}
}
public static void Print(Node head)
{
if (head == null) return;
Node current = head;
do {
Console.WriteLine(current.Data);
current = current.Next;
} while (current != null);
}
public static void Reverse(ref Node head)
{
if (head == null) return;
Node prev = null, current = head, next = null;
while(current.Next != null)
{
next = current.Next;
current.Next = prev;
prev = current;
current = next;
}
current.Next = prev;
head = current;
}
public static Node current;
public static Node ReverseRecursive(Node head, Node prev)
{
if (head == null) return null;
if (head.Next == null)
{
current = head;
current.Next = prev;
return null;
}
Node next = head.Next;
head.Next = prev;
ReverseRecursive(next, head);
return current;
}
}
public class Node
{
public int Data = 0;
public Node Next = null;
}
}
}