在O(1)时间删除指定链表结点

时间:2022-05-04 09:56:59
    #region 在O(1)时间删除指定链表结点
/// <summary>
/// 给定单向链表的头指针和一个结点指针,定义一个函数在O(1)时间删除该结点。
/// </summary>
/// <typeparam name="T"></typeparam>
class MyList<T> where T:IComparable
{
private T _data;
private MyList<T> _next; public T data
{
get { return _data; }
set { _data = value; }
}
public MyList<T> next
{
get { return _next; }
set { _next = value; }
} public MyList()
{
data = default(T);
next = null;
}
public MyList(T nodevalue)
{
data = nodevalue;
next = null;
}
public void Insert(MyList<T> head,MyList<T> node)
{
if (head == null)
{
head = new MyList<T>();
head = node;
}
else
{
node.next = head.next;
head.next = node;
}
}
public void Insert(MyList<T> head, T nodevalue)
{
MyList<T> temp = new MyList<T>(nodevalue);
if (head == null)
{
head = temp;
}
else
{
temp.next = head.next;
head.next = temp;
}
}
public void Delete(MyList<T> head, MyList<T> deleteNode)
{
if ((deleteNode==null)||(head==null)) return;
if (deleteNode == head)
{
head = null;
deleteNode = null;
}
else if (deleteNode.next == null)
{
MyList<T> pNode = new MyList<T>();
pNode = head;
while (pNode.next != deleteNode)
pNode = pNode.next;
pNode.next = null;
deleteNode = null;
}
else
{
MyList<T> pNext = new MyList<T>();
pNext = deleteNode.next;
deleteNode.data = pNext.data;
deleteNode.next = pNext.next;
pNext = null;
}
}
public void Print(MyList<T> head)
{
MyList<T> pNode = head;
while (pNode != null)
{
Console.Write(pNode.data + " ");
pNode = pNode.next; }
Console.WriteLine();
}
}
#endregion
class Test{
public void MyListTest()
{
MyList<int> head = new MyList<int>(1);
head.Insert(head,2);
MyList<int> WishDelete = new MyList<int>(4);
head.Insert(head, WishDelete);
head.Insert(head,3);
head.Print(head);
head.Delete(head,WishDelete);
head.Print(head);
}
}
class Program
{ static void Main(string[] args)
{
Test t = new Test();
t.MyListTest();
}
}

在O(1)时间删除指定链表结点