hi
i want to reverse the LL useing recurtion in C#, i am able to print it in reverse order but unable to store it as LL in reverse order,
below is the code for it ::)

using System;
using System.Collections.Generic;
using System.Text;
namespace linearLL
{
class LinkList
{
public string Val;
public object NextItem;

[STAThread]
static void Main(string[] args)
{
LinkList obList = new LinkList();
obList.Val = "Head";
LinkList obHead = obList;
LinkList tmphead = obList;
// Add 10 items to the list.
for (int i = 0; i < 5; i++)
{
obList.NextItem = new LinkList();
obList = (LinkList)obList.NextItem;
obList.Val = i.ToString();
}
//obList.Val = null;
//obList.NextItem = null;
// Print the added items.
while (obHead != null)
{
Console.WriteLine("Item: {0}", obHead.Val);
obHead = (LinkList)obHead.NextItem;
}

Console.WriteLine("Reversing Link List");
Console.ReadLine();
Reverse r = new Reverse();
LinkList objrev = obList;
objrev= r.RevLL(tmphead.NextItem);

// Print the reversed items.
while (objrev != null)
{
Console.WriteLine("Item: {0}", objrev.Val);
objrev = (LinkList) objrev.NextItem;
}
Console.ReadLine();
}
}
 
class Reverse
{
LinkList obrev = new LinkList();

public LinkList RevLL(object NewLL)
{
LinkList NewL = (LinkList)NewLL;
if (NewL.NextItem != null)
{
RevLL(NewL.NextItem);
}
Console.WriteLine(NewL.Val.ToString());
obrev.NextItem = new LinkList();
obrev = (LinkList) obrev.NextItem;
obrev.Val = NewL.Val.ToString();
return obrev;
}
 
}
}

:sad:

Hi,

Your code is confusing and require some cleaning up. I suggest that you put the ststic void main in a separate class than your base classes. The class name LinkList is misleading because as far as I understand that class is implemented as a single element of a LL (you may name it linkListElement). You don't need to type parameters as Object and cast them back to LinkList class, use directly LinkListElement as NextItem and the parameter of RevLL (thus no need for NevLL to NewL conversion).
Your main problem is that you discard the value you return with "return obrev;" on

if (NewL.NextItem != null)
{
/* assign the return value to something here =*/ RevLL(NewL.NextItem);
}

To what the assignement should be made is left as an exercise to the reader. ;)

Loren Soth

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.