私はデータ構造に不慣れで、これが非常によくある質問であることを知っています。しかし、.NET の LinkedList が二重にリンクされていることはわかっているので、C# で単一リンク リストのコードを記述する方法を教えてください。
誰かサンプルコードを書いてくれませんか?
私はデータ構造に不慣れで、これが非常によくある質問であることを知っています。しかし、.NET の LinkedList が二重にリンクされていることはわかっているので、C# で単一リンク リストのコードを記述する方法を教えてください。
誰かサンプルコードを書いてくれませんか?
ここでは再帰を使用しています。
private void Reverse(Item item)
{
if (item == null || item.Next == null) //if head is null or we are at the tail
{
this.Head = item; //we are at the tail or empty list, set the new head to the tail
return;
}
Reverse(item.Next);
var nextItem = item.Next; //get the next item out, dealing with references don't want to override it
item.Next = null; //once you get the next item out, you can delete the *reference* i.e. link to it
nextItem.Next = item; //set the item you got out link to next item to the current item i.e. reverse it
}
ループを使用 (現在の要素: currentNode、ループ外で初期化された変数: previousNode、nextNode)
Set nextNode = currentNode.NextNode
Set currentNode.NextNode = previousNode
Set previousNode = currentNode
Set currentNode = nextNode
continue with loop
いくつかのデータとリンクリスト内の次のノードへの参照を含むノードデータ構造を定義する必要があります。何かのようなもの:
class Node {
private Node _next;
private string _data;
public Node(string data) {
_next = null;
_data = data;
}
// TODO: Property accessors and functions to link up the list
}
次に、リストを逆の順序でループして、新しい逆のリストを作成するアルゴリズムを作成できます。
reversed_list = new
for all node in the original list
insert the node to the head of reversed_list
ここでは、.net (C#) でリンクされた反転の反復と再帰を示します (リンクされたリストは、最初と最後のポインターの両方を維持しているため、O(1) の末尾に追加したり、先頭に挿入したりできます-行う必要はありませんこれ. リンク リストの動作を上記のように定義したところです)
public void ReverseIterative()
{
if(null == first)
{
return;
}
if(null == first.Next)
{
return;
}
LinkedListNode<T> p = null, f = first, n = null;
while(f != null)
{
n = f.Next;
f.Next = p;
p = f;
f = n;
}
last = first;
first = p;
}
再帰的:
public void ReverseRecursive()
{
if (null == first)
{
return;
}
if (null == first.Next)
{
return;
}
last = first;
first = this.ReverseRecursive(first);
}
private LinkedListNode<T> ReverseRecursive(LinkedListNode<T> node)
{
Debug.Assert(node != null);
var adjNode = node.Next;
if (adjNode == null)
{
return node;
}
var rf = this.ReverseRecursive(adjNode);
adjNode.Next = node;
node.Next = null;
return rf;
}
これは宿題である可能性が高いため、すべての作業を行わないように、かなり紛らわしい方法でこれを述べます。うまくいけば、私の試みが物事をより混乱させるだけではありません (これは非常に可能性があります)。
リスト内のノード (最初のノードなど) への参照がある場合は、それに続くノードへの参照もあります。同様の作業を実行するには、次のノード (およびその前の状態) に関する十分な情報を保持しながら、次のノードが現在のノードを参照するようにする必要があります。ここで注意が必要な部分は、境界条件 (リストの開始と終了) を処理することだけです。