0

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 ?

2 Answers2

0

Something like this should work

static Node<int> ReverseNode(Node<int> chain)
{
    Node<int> lastNode = new Node<int>(chain.GetInfo());
    Node<int> currentNode = chain.GetNext();
    while(currentNode != null)
    {
        Node<int> nextNode = new Node<int>(currentNode.GetInfo(),lastNode);
        lastNode = nextNode;
        currentNode = currentNode.GetNext();
    }
    return lastNode;
}
woot ness
  • 51
  • 3
0

Recursive version:

public static Node<int> ReverseNode(Node<int> chain)
    {
        if (chain.GetNext() == null)
            return chain;

        var reversedChain = ReverseNode(chain.GetNext());

        chain.GetNext().SetNext(chain);
        chain.SetNext(null);

        return reversedChain;
    }
user707727
  • 1,287
  • 7
  • 16