我不确定如何实现Linked List Insert方法。我知道我需要创建一个新的node()遍历列表,我知道如何做到这一点,但我不确定插入是如何工作的,它不像数组那么简单。
想知道是否有人可以帮忙解释我是如何构建这样的方法的。
答案 0 :(得分:1)
我试着做一个样本。也许你会发现它很方便
using System;
namespace LinkedList
{
class LinkedList
{
public static void Main(String[] args){
var list = new LinkedList();
list.Insert (1);
list.Insert (2);
list.Insert (3);
list.Insert (4);
var node = list.Head;
do {
Console.Out.WriteLine (node.Value);
} while((node = node.Next) != null);
}
private Node _dummy;
private Node _head;
private Node _tail;
public Node Head { get { return _head; }}
public LinkedList(){
_dummy = new Node(null, null);
_head = _dummy;
_tail = _dummy;
}
public void Insert(int value){
_head = new Node(_head, value);
}
public class Node{
public int? Value { get; set; }
public Node Next { get; set;}
public Node(Node next, int? value){
Value = value;
Next = next;
}
}
}
}
答案 1 :(得分:0)
Node head;
object key;
Node nodeTobeInserted;
void Insert(object key)
{
if(head == null)
head = new Node();
else if(head.value.Equals(key))
{
Node next = head.Next;
head=nodeToBeInserted;
head.Next = next;
}
else
{
do
{
Node next = head.next;
}
while(next.Next != null && next.Next.value != key);
if(next.Next !=null)
{
nodeTobeInserted.Next = node.Next;
node.Next = nodeToBeInserted;
}
}
}
// Sample Code, but yeah this might give you an idea how to do it