Created
February 12, 2019 07:11
-
-
Save yinyue200/7abd6bcdf85af85d7f7e0ec51116debb to your computer and use it in GitHub Desktop.
SinglyLinkedList.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//********************************************************* | |
// | |
// Copyright (c) yinyue200.com. All rights reserved. | |
// This code is licensed under the MIT License (MIT). | |
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF | |
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY | |
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR | |
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. | |
// | |
//********************************************************* | |
class SinglyLinkedList<T>:ICollection<T>,IReadOnlyCollection<T> | |
{ | |
SingleLinkedNode<T> Head; | |
SingleLinkedNode<T> Tail; | |
public int Count { get; private set; } = 0; | |
public bool IsReadOnly => false; | |
public void Add(T item) | |
{ | |
if (Head == null) | |
{ | |
Head = new SingleLinkedNode<T>(item); | |
Tail = Head; | |
Count = 1; | |
} | |
else | |
{ | |
var node = new SingleLinkedNode<T>(item); | |
Tail.Next = node; | |
Tail = node; | |
Count++; | |
} | |
} | |
public void Clear() | |
{ | |
Tail = null; | |
Head = null; | |
Count = 0; | |
} | |
public bool Contains(T item) => System.Linq.Enumerable.Contains(this, item); | |
public void CopyTo(T[] array, int arrayIndex) | |
{ | |
SingleLinkedNode<T> node = Head; | |
for (var i = arrayIndex; i < array.Length; i++) | |
{ | |
array[i] = node.Value; | |
node = node.Next; | |
} | |
} | |
public IEnumerator<T> GetEnumerator() | |
{ | |
SingleLinkedNode<T> node = Head; | |
while (true) | |
{ | |
if (node == null) | |
break; | |
yield return node.Value; | |
node = node.Next; | |
} | |
} | |
public bool Remove(T item) | |
{ | |
int rmcount = 0; | |
SingleLinkedNode<T> lnode = null; | |
SingleLinkedNode<T> node = Head; | |
while (true) | |
{ | |
if (node == null) | |
break; | |
if (EqualityComparer<T>.Default.Equals(item, node.Value)) | |
{ | |
if (lnode == null) | |
{ | |
Head = node.Next; | |
} | |
else | |
{ | |
lnode.Next = node.Next; | |
} | |
if(node.Next==null) | |
{ | |
Tail = lnode; | |
} | |
rmcount++; | |
} | |
lnode = node; | |
node = node.Next; | |
} | |
Count -= rmcount; | |
return rmcount > 0; | |
} | |
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); | |
private sealed class SingleLinkedNode<TValue> | |
{ | |
public SingleLinkedNode(TValue NewValue) | |
{ | |
Value = NewValue; | |
} | |
public SingleLinkedNode<TValue> Next; | |
public TValue Value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment