Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Text;
- namespace DictionaryWorkshop.Implementation
- {
- public class MyLinkedList<TKey, TValue> : IEnumerable<MyKeyValuePair<TKey,TValue>>
- {
- public MyKeyValuePair<TKey, TValue> Head { get; private set; }
- public MyKeyValuePair<TKey, TValue> Tail { get; private set; }
- public MyLinkedList(TKey key, TValue value)
- {
- this.Head = new MyKeyValuePair<TKey, TValue>(key, value);
- this.Tail = this.Head;
- this.Count++;
- }
- public int Count { get; set; }
- public bool Add(TKey key, TValue value)
- {
- var oldTail = this.Tail;
- var newNode = new MyKeyValuePair<TKey, TValue>(key, value);
- if (this.Count == 0 && this.Contains(key)==false)
- {
- this.Tail = newNode;
- this.Head = this.Tail;
- this.Count++;
- return true;
- }
- else if (this.Contains(key) == false)
- {
- oldTail.Next = newNode;
- this.Tail = newNode;
- this.Count++;
- return true;
- }
- return false;
- }
- public bool Remove(TKey key)
- {
- MyKeyValuePair<TKey, TValue> current = this.Head;
- if (this.Count == 0)
- {
- throw new InvalidOperationException();
- }
- if (this.Contains(key)==false )
- {
- return false;
- }
- if (this.Head.Key.Equals(key) && this.Tail.Key.Equals(key))
- {
- this.Head = null;
- this.Tail = null;
- this.Count--;
- return true;
- }
- else if (this.Tail.Key.Equals(key))
- {
- var currentNode = this.Head;
- while (currentNode !=null)
- {
- if (currentNode.Next == this.Tail)
- {
- currentNode.Next = null;
- currentNode = this.Tail;
- this.Count--;
- return true;
- }
- currentNode = currentNode.Next;
- }
- }
- while (current !=null)
- {
- if (current.Next.Key.Equals(key))
- {
- var previous = current;
- previous.Next = previous.Next.Next;
- this.Count--;
- return true;
- }
- current = current.Next;
- }
- return false;
- }
- public bool Contains(TKey key)
- {
- MyKeyValuePair<TKey, TValue> current = this.Head;
- while (current !=null)
- {
- if (current.Key.Equals(key))
- {
- return true;
- }
- current = current.Next;
- }
- return false;
- }
- public IEnumerator<MyKeyValuePair<TKey, TValue>> GetEnumerator()
- {
- MyKeyValuePair<TKey, TValue> current = this.Head;
- while (current != null)
- {
- yield return current;
- current = current.Next;
- }
- }
- IEnumerator IEnumerable.GetEnumerator()
- {
- return GetEnumerator();
- }
- public override string ToString()
- {
- var sb = new StringBuilder();
- var temp = this.Head;
- while (temp !=null)
- {
- sb.AppendLine(temp.ToString());
- temp = temp.Next;
- }
- return sb.ToString();
- }
- }
- }
Add Comment
Please, Sign In to add comment