构造线性列表插入方法
本文关键字:插入 方法 列表 线性 | 更新日期: 2023-09-27 18:30:33
我不确定如何实现链表插入方法。我知道我需要创建一个新的node()遍历列表,我知道该怎么做,但我不确定插入是如何工作的,它不像数组那么简单。
想知道是否有人可以帮忙并解释我如何构建这样的方法。
我试图做一个样本。也许你会发现它很方便
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;
}
}
}
}
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