Created
September 24, 2014 11:59
-
-
Save AlexArchive/c46c0ca6c3a73aec3d49 to your computer and use it in GitHub Desktop.
This file contains 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
public class LinkedListNode<TNode> | |
{ | |
public TNode Value | |
{ | |
get; | |
set; | |
} | |
public LinkedListNode<TNode> Next | |
{ | |
get; | |
set; | |
} | |
public LinkedListNode(TNode value) | |
{ | |
Value = value; | |
} | |
} | |
public class LinkedList<TNode> : IEnumerable<TNode> | |
{ | |
public LinkedListNode<TNode> Head | |
{ | |
get; | |
private set; | |
} | |
public LinkedListNode<TNode> Tail | |
{ | |
get; | |
private set; | |
} | |
public int Count | |
{ | |
get; | |
private set; | |
} | |
public void AddFirst(TNode value) | |
{ | |
AddFirst(new LinkedListNode<TNode>(value)); | |
} | |
public void AddFirst(LinkedListNode<TNode> node) | |
{ | |
LinkedListNode<TNode> temp = Head; | |
Head = node; | |
node.Next = temp; | |
Count += 1; | |
if (Count == 1) | |
{ | |
Tail = Head; | |
} | |
} | |
public void AddLast(TNode value) | |
{ | |
AddLast(new LinkedListNode<TNode>(value)); | |
} | |
public void AddLast(LinkedListNode<TNode> node) | |
{ | |
if (Count == 0) | |
{ | |
Head = node; | |
} | |
else | |
{ | |
Tail.Next = node; | |
} | |
Tail = node; | |
Count += 1; | |
} | |
public void RemoveFirst() | |
{ | |
if (Count != 0) | |
{ | |
Head = Head.Next; | |
Count -= 1; | |
if (Count == 0) | |
{ | |
Tail = null; | |
} | |
} | |
} | |
public void RemoveLast() | |
{ | |
if (Count != 0) | |
{ | |
if (Count == 1) | |
{ | |
Head = null; | |
Tail = null; | |
} | |
else | |
{ | |
var current = Head; | |
while (current.Next != Tail) | |
{ | |
current = current.Next; | |
} | |
current.Next = null; | |
Tail = current; | |
} | |
Count -= 1; | |
} | |
} | |
public bool Contains(TNode value) | |
{ | |
return Enumerable.Contains(this, value); | |
} | |
public IEnumerator<TNode> GetEnumerator() | |
{ | |
var current = Head; | |
while (current != null) | |
{ | |
yield return current.Value; | |
current = current.Next; | |
} | |
} | |
IEnumerator IEnumerable.GetEnumerator() | |
{ | |
return GetEnumerator(); | |
} | |
public void Clear() | |
{ | |
Head = null; | |
Tail = null; | |
Count = 0; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment