How can I reverse a linked Node ... ?
Simply I want to make a function that reverses a linked Node , The title of the function will be
public static Node<int> ReverseNode(Node<int> chain)
{
//...
}
For Ex. The Recieved Node is [10->5->7] The returned Node Should be [7->5->10]
the node class is Below ..
using System;
using System.Collections.Generic; using System.Text;
public class Node<T>
{
private T info;
private Node<T> next;
public Node(T x)
{
this.info = x;
this.next = null;
}
public Node(T x, Node<T> next)
{
this.info = x;
this.next = next;
}
public T GetInfo()
{
return (this.info);
}
public void SetInfo(T x)
{
this.info = x;
}
public Node<T> GetNext()
{
return (this.next);
}
public void SetNext(Node<T> next)
{
this.next = next;
}
public override string ToString()
{
return ("" + this.info + "-->");
}
}
tried doing this but it didn't work for some reason... why ?
public Node<T> reverse()
{
Node<T> chain1 = data.GetFirst();
Node<T> chain2 = new Node<T>(chain1.GetInfo());
Node<T> p = chain1.GetNext() ;
while (p != null)
{
Node <T> Tmp = p.GetNext();
p.SetNext(chain2);
chain2 = p;
p = Tmp;
}
Console.WriteLine( chain2.ToString());
return chain2;
}
Could you please tell me what is wrong with my code ?