2016-02-27 88 views
0

如何扭转链接的节点...?扭转链接的节点

只要我想做出一个反向链接节点的功能,该功能的标题将是 public static Node<int> ReverseNode(Node<int> chain) { //... }

对于防爆。在收到节点是[10-> 5-> 7] 返回的节点应该是[7-> 5-> 10]

节点类是下面..

using System; 

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 + "-->"); 
    } 
} 

试过这样做,但它并没有出于某种原因...为什么?

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

请问您能告诉我我的代码出了什么问题吗?

+0

你需要一个双链接列表,而不是链接列表或使用缓冲区进行数据复制到。 –

+0

嗯,我有一个类,我只能使用该类别人... –

+1

可能的重复[在C#中反转单链表](http://stackoverflow.com/questions/8686168/reversing-single-linked-list -in-c-sharp) –

回答

0

像这样的东西应该工作

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

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

+0

@MohammedKhalaila推荐阅读 - http://ericlippert.com/2014/03/05/how-to-debug-small-programs/ –

0

递归版本:

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