【问题标题】:Reversing A Linked Node反转链接节点
【发布时间】:2016-06-10 19:47:28
【问题描述】:

如何反转链接节点...?

我只想制作一个反转链接节点的函数,函数的标题将是 public static Node<int> ReverseNode(Node<int> chain) { //... }

例如。收到的节点是 [10->5->7] 返回的节点应该是[7->5->10]

节点类在下方..

using System;

使用 System.Collections.Generic; 使用 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 + "-->");
    }
}

尝试这样做,但由于某种原因它不起作用......为什么?

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;
}

你能告诉我我的代码有什么问题吗?

【问题讨论】:

  • 你需要一个双链表而不是链表或者使用缓冲区来复制数据。
  • 好吧,我有一门课,我只能用那门课……
  • 这不是重复的......
  • @MohammedKhalaila 那到底怎么不是重复的?

标签: c# nodes


【解决方案1】:

递归版本:

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;
    }

【讨论】:

    【解决方案2】:

    这样的东西应该可以工作

    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;
    }
    

    【讨论】:

    猜你喜欢
    • 2015-06-15
    • 2011-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-25
    • 2015-05-11
    相关资源
    最近更新 更多