本文介绍了扭转了C#单链表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图扭转一个链表。这是代码我想出了:
公共静态无效的反转(参考节点根)
{
节点TMP =根;
节点nroot = NULL;
节点上一个= NULL;
,而(!TMP = NULL)
{
//创建一个新的节点,并复制TMP
nroot =新节点();
nroot.data = tmp.data;
nroot.next =上一页;
=上一张nroot;
TMP = tmp.next;
}
根= nroot;
}
这是运作良好。想知道是否有可能避免产生新的节点。想对这个建议。
解决方案
节点p =根,N = NULL ;
,而(P!= NULL){
节点TMP = p.next;
p.next = N;
N = P;
P = TMP;
}
根= N;
I am trying to reverse a linked list. This is the code I have come up with:
public static void Reverse(ref Node root)
{
Node tmp = root;
Node nroot = null;
Node prev = null;
while (tmp != null)
{
//Make a new node and copy tmp
nroot = new Node();
nroot.data = tmp.data;
nroot.next = prev;
prev = nroot;
tmp = tmp.next;
}
root = nroot;
}
It is working well. Was wondering if it possible to avoid creating new node. Would like to have suggestions on this.
解决方案
Node p = root, n = null;
while (p != null) {
Node tmp = p.next;
p.next = n;
n = p;
p = tmp;
}
root = n;
这篇关于扭转了C#单链表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!