Ai
1 Star 1 Fork 0

AndyZhang/C-Sharp-Algorithms

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
DLinkedList.cs 25.77 KB
一键复制 编辑 原始数据 按行查看 历史
Ivandro Ismael 提交于 2018-05-21 07:50 +08:00 . remove redundant "else" / "else if"
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
using System;
using System.Collections.Generic;
using DataStructures.Common;
namespace DataStructures.Lists
{
/// <summary>
/// The Doubly-Linked List Node class.
/// </summary>
/// <typeparam name="T">Type</typeparam>
public class DLinkedListNode<T> : IComparable<DLinkedListNode<T>> where T : IComparable<T>
{
private T _data;
private DLinkedListNode<T> _next;
private DLinkedListNode<T> _previous;
public DLinkedListNode() : this(default(T)) { }
public DLinkedListNode(T dataItem) : this(dataItem, null, null) { }
public DLinkedListNode(T dataItem, DLinkedListNode<T> next, DLinkedListNode<T> previous)
{
Data = dataItem;
Next = next;
Previous = previous;
}
public virtual T Data
{
get { return this._data; }
set { this._data = value; }
}
public virtual DLinkedListNode<T> Next
{
get { return this._next; }
set { this._next = value; }
}
public virtual DLinkedListNode<T> Previous
{
get { return this._previous; }
set { this._previous = value; }
}
public int CompareTo(DLinkedListNode<T> other)
{
if (other == null) return -1;
return this.Data.CompareTo(other.Data);
}
}
/***********************************************************************************/
/// <summary>
/// Doubly-Linked List Data Structure.
/// </summary>
/// <typeparam name="T">Type</typeparam>
public class DLinkedList<T> : IEnumerable<T> where T : IComparable<T>
{
/// <summary>
/// Instance variables.
/// </summary>
private int _count;
private DLinkedListNode<T> _firstNode { get; set; }
private DLinkedListNode<T> _lastNode { get; set; }
public virtual DLinkedListNode<T> Head
{
get { return this._firstNode; }
}
public virtual int Count
{
get { return this._count; }
}
/// <summary>
/// Gets the element at the specified index
/// </summary>
/// <param name="index">Index of element</param>
/// <returns>Element</returns>
protected virtual T _getElementAt(int index)
{
if (IsEmpty() || index < 0 || index >= Count)
throw new IndexOutOfRangeException("List is empty.");
if (index == 0)
{
return First;
}
if (index == (Count - 1))
{
return Last;
}
DLinkedListNode<T> currentNode = null;
// Decide from which reference to traverse the list, and then move the currentNode reference to the index
// If index > half then traverse it from the end (_lastNode reference)
// Otherwise, traverse it from the beginning (_firstNode refrence)
if (index > (Count / 2))
{
currentNode = this._lastNode;
for (int i = (Count - 1); i > index; --i)
{
currentNode = currentNode.Previous;
}
}
else
{
currentNode = this._firstNode;
for (int i = 0; i < index; ++i)
{
currentNode = currentNode.Next;
}
}
return currentNode.Data;
}
/// <summary>
/// Sets the value of the element at the specified index
/// </summary>
/// <param name="index">Index of element to update.</param>
/// <returns>Element</returns>
protected virtual void _setElementAt(int index, T value)
{
if (IsEmpty() || index < 0 || index >= Count)
throw new IndexOutOfRangeException("List is empty.");
if (index == 0)
{
_firstNode.Data = value;
}
else if (index == (Count - 1))
{
_lastNode.Data = value;
}
else
{
DLinkedListNode<T> currentNode = null;
// Decide from which reference to traverse the list, and then move the currentNode reference to the index
// If index > half then traverse it from the end (_lastNode reference)
// Otherwise, traverse it from the beginning (_firstNode refrence)
if (index > (Count / 2))
{
currentNode = this._lastNode;
for (int i = (Count - 1); i > index; --i)
{
currentNode = currentNode.Previous;
}
}
else
{
currentNode = this._firstNode;
for (int i = 0; i < index; ++i)
{
currentNode = currentNode.Next;
}
}
currentNode.Data = value;
}
}
/// <summary>
/// CONSTRUCTOR
/// </summary>
public DLinkedList()
{
_count = 0;
_firstNode = null;
_lastNode = null;
}
/// <summary>
/// Determines whether this List is empty.
/// </summary>
/// <returns><c>true</c> if this list is empty; otherwise, <c>false</c>.</returns>
public virtual bool IsEmpty()
{
return (Count == 0);
}
/// <summary>
/// Getter function that returns the first element
/// </summary>
public virtual T First
{
get
{
if (IsEmpty())
{
throw new Exception("Empty list.");
}
return _firstNode.Data;
}
}
/// <summary>
/// Getter function that returns the last element
/// </summary>
public virtual T Last
{
get
{
if (IsEmpty())
{
throw new Exception("Empty list.");
}
if (_lastNode == null)
{
var currentNode = _firstNode;
while (currentNode.Next != null)
{
currentNode = currentNode.Next;
}
_lastNode = currentNode;
return currentNode.Data;
}
return _lastNode.Data;
}
}
/// <summary>
/// Implements the collection-index operator.
/// Gets or sets the element at the specified index
/// </summary>
/// <param name="index">Index of element.</param>
public virtual T this[int index]
{
get { return this._getElementAt(index); }
set { this._setElementAt(index, value); }
}
/// <summary>
/// Returns the index of an item if exists.
/// </summary>
public virtual int IndexOf(T dataItem)
{
int i = 0;
bool found = false;
var currentNode = _firstNode;
// Get currentNode to reference the element at the index.
while (i < Count)
{
if (currentNode.Data.IsEqualTo(dataItem))
{
found = true;
break;
}
currentNode = currentNode.Next;
i++;
}//end-while
return (found == true ? i : -1);
}
/// <summary>
/// Prepend the specified dataItem at the beginning of the list.
/// </summary>
/// <param name="dataItem">Data item.</param>
public virtual void Prepend(T dataItem)
{
DLinkedListNode<T> newNode = new DLinkedListNode<T>(dataItem);
if (_firstNode == null)
{
_firstNode = _lastNode = newNode;
}
else
{
var currentNode = _firstNode;
newNode.Next = currentNode;
currentNode.Previous = newNode;
_firstNode = newNode;
}
// Increment the count.
_count++;
}
/// <summary>
/// Append the specified dataItem at the end of the list.
/// </summary>
/// <param name="dataItem">Data item.</param>
public virtual void Append(T dataItem)
{
DLinkedListNode<T> newNode = new DLinkedListNode<T>(dataItem);
if (_firstNode == null)
{
_firstNode = _lastNode = newNode;
}
else
{
var currentNode = _lastNode;
currentNode.Next = newNode;
newNode.Previous = currentNode;
_lastNode = newNode;
}
// Increment the count.
_count++;
}
/// <summary>
/// Inserts the dataItem at the specified index.
/// </summary>
/// <param name="dataItem">Data item.</param>
/// <param name="index">Index.</param>
public virtual void InsertAt(T dataItem, int index)
{
if(index < 0 || index > Count)
throw new IndexOutOfRangeException();
if (index == 0)
{
Prepend(dataItem);
}
else if (index == Count)
{
Append(dataItem);
}
else
{
DLinkedListNode<T> currentNode = null;
DLinkedListNode<T> newNode = new DLinkedListNode<T>(dataItem);
currentNode = this._firstNode;
for (int i = 0; i < index - 1; ++i)
{
currentNode = currentNode.Next;
}
var oldNext = currentNode.Next;
if (oldNext != null)
currentNode.Next.Previous = newNode;
newNode.Next = oldNext;
currentNode.Next = newNode;
newNode.Previous = currentNode;
// Increment the count
_count++;
}
}
/// <summary>
/// Inserts the dataItem after specified index.
/// </summary>
/// <param name="dataItem">Data item.</param>
/// <param name="index">Index.</param>
public virtual void InsertAfter(T dataItem, int index)
{
// Insert at previous index.
InsertAt(dataItem, index - 1);
}
/// <summary>
/// Remove the specified dataItem.
/// </summary>
public virtual void Remove(T dataItem)
{
// Handle index out of bound errors
if (IsEmpty())
throw new IndexOutOfRangeException();
if (_firstNode.Data.IsEqualTo(dataItem))
{
_firstNode = _firstNode.Next;
if (_firstNode != null)
_firstNode.Previous = null;
}
else if (_lastNode.Data.IsEqualTo(dataItem))
{
_lastNode = _lastNode.Previous;
if (_lastNode != null)
_lastNode.Next = null;
}
else
{
// Remove
var currentNode = _firstNode;
// Get currentNode to reference the element at the index.
while (currentNode.Next != null)
{
if (currentNode.Data.IsEqualTo(dataItem))
break;
currentNode = currentNode.Next;
}//end-while
// Throw exception if item was not found
if (!currentNode.Data.IsEqualTo(dataItem))
throw new Exception("Item was not found!");
// Remove element
DLinkedListNode<T> newPrevious = currentNode.Previous;
DLinkedListNode<T> newNext = currentNode.Next;
if (newPrevious != null)
newPrevious.Next = newNext;
if (newNext != null)
newNext.Previous = newPrevious;
currentNode = newPrevious;
}
// Decrement count.
_count--;
}
/// <summary>
/// Remove the specified dataItem.
/// </summary>
public virtual void RemoveFirstMatch(Predicate<T> match)
{
// Handle index out of bound errors
if (IsEmpty())
throw new IndexOutOfRangeException();
if (match(_firstNode.Data))
{
_firstNode = _firstNode.Next;
if (_firstNode != null)
_firstNode.Previous = null;
}
else if (match(_lastNode.Data))
{
_lastNode = _lastNode.Previous;
if (_lastNode != null)
_lastNode.Next = null;
}
else
{
// Remove
var currentNode = _firstNode;
// Get currentNode to reference the element at the index.
while (currentNode.Next != null)
{
if (match(currentNode.Data))
break;
currentNode = currentNode.Next;
}//end-while
// If we reached the last node and item was not found
// Throw exception
if (!match(currentNode.Data))
throw new Exception("Item was not found!");
// Remove element
DLinkedListNode<T> newPrevious = currentNode.Previous;
DLinkedListNode<T> newNext = currentNode.Next;
if (newPrevious != null)
newPrevious.Next = newNext;
if (newNext != null)
newNext.Previous = newPrevious;
currentNode = newPrevious;
}
// Decrement count.
_count--;
}
/// <summary>
/// Removes the item at the specified index.
/// </summary>
/// <returns>True if removed successfully, false otherwise.</returns>
/// <param name="index">Index of item.</param>
public virtual void RemoveAt(int index)
{
// Handle index out of bound errors
if (IsEmpty() || index < 0 || index >= Count)
throw new IndexOutOfRangeException();
// Remove
if (index == 0)
{
_firstNode = _firstNode.Next;
if (_firstNode != null)
_firstNode.Previous = null;
}
else if (index == Count - 1)
{
_lastNode = _lastNode.Previous;
if (_lastNode != null)
_lastNode.Next = null;
}
else
{
int i = 0;
var currentNode = _firstNode;
// Get currentNode to reference the element at the index.
while (i < index)
{
currentNode = currentNode.Next;
i++;
}//end-while
// Remove element
var newPrevious = currentNode.Previous;
var newNext = currentNode.Next;
newPrevious.Next = newNext;
if (newNext != null)
newNext.Previous = newPrevious;
currentNode = newPrevious;
}//end-else
// Decrement count.
_count--;
}
/// <summary>
/// Clears the list.
/// </summary>
public virtual void Clear()
{
_count = 0;
_firstNode = _lastNode = null;
}
/// <summary>
/// Chesk whether the specified element exists in the list.
/// </summary>
/// <param name="dataItem">Value to check for.</param>
/// <returns>True if found; false otherwise.</returns>
public virtual bool Contains(T dataItem)
{
try
{
return Find(dataItem).IsEqualTo(dataItem);
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// Find the specified item in the list.
/// </summary>
/// <param name="dataItem">Value to find.</param>
/// <returns>value.</returns>
public virtual T Find(T dataItem)
{
if (IsEmpty())
throw new Exception("List is empty.");
var currentNode = _firstNode;
while (currentNode != null)
{
if (currentNode.Data.IsEqualTo(dataItem))
return dataItem;
currentNode = currentNode.Next;
}
throw new Exception("Item was not found.");
}
/// <summary>
/// Tries to find a match for the predicate. Returns true if found; otherwise false.
/// </summary>
public virtual bool TryFindFirst(Predicate<T> match, out T found)
{
// Initialize the output parameter
found = default(T);
if (IsEmpty())
return false;
var currentNode = _firstNode;
try
{
while (currentNode != null)
{
if (match(currentNode.Data))
{
found = currentNode.Data;
return true;
}
currentNode = currentNode.Next;
}
return false;
}
catch
{
return false;
}
}
/// <summary>
/// Find the first element that matches the predicate from all elements in list.
/// </summary>
public virtual T FindFirst(Predicate<T> match)
{
if (IsEmpty())
throw new Exception("List is empty.");
var currentNode = _firstNode;
while (currentNode != null)
{
if (match(currentNode.Data))
return currentNode.Data;
currentNode = currentNode.Next;
}
throw new KeyNotFoundException();
}
/// <summary>
/// Find all elements in list that match the predicate.
/// </summary>
/// <param name="match">Predicate function.</param>
/// <returns>List of elements.</returns>
public virtual List<T> FindAll(Predicate<T> match)
{
if (IsEmpty())
throw new Exception("List is empty.");
var currentNode = _firstNode;
var list = new List<T>();
while (currentNode != null)
{
if (match(currentNode.Data))
list.Add(currentNode.Data);
currentNode = currentNode.Next;
}
return list;
}
/// <summary>
/// Returns a number of elements as specified by countOfElements, starting from the specified index.
/// </summary>
/// <param name="index">Starting index.</param>
/// <param name="countOfElements">The number of elements to return.</param>
/// <returns>Doubly-Linked List of elements</returns>
public virtual DLinkedList<T> GetRange(int index, int countOfElements)
{
DLinkedListNode<T> currentNode = null;
DLinkedList<T> newList = new DLinkedList<T>();
// Handle Index out of Bound errors
if (Count == 0)
{
return newList;
}
if (index < 0 || index > Count)
{
throw new IndexOutOfRangeException();
}
// Decide from which reference to traverse the list, and then move the currentNode reference to the index
// If index > half then traverse it from the end (_lastNode reference)
// Otherwise, traverse it from the beginning (_firstNode refrence)
if (index > (Count / 2))
{
currentNode = this._lastNode;
for (int i = (Count - 1); i > index; --i)
{
currentNode = currentNode.Previous;
}
}
else
{
currentNode = this._firstNode;
for (int i = 0; i < index; ++i)
{
currentNode = currentNode.Next;
}
}
// Append the elements to the new list using the currentNode reference
while (currentNode != null && newList.Count <= countOfElements)
{
newList.Append(currentNode.Data);
currentNode = currentNode.Next;
}
return newList;
}
/// <summary>
/// Sorts the entire list using Selection Sort.
/// </summary>
public virtual void SelectionSort()
{
if (IsEmpty())
return;
var currentNode = _firstNode;
while (currentNode != null)
{
var nextNode = currentNode.Next;
while (nextNode != null)
{
if (nextNode.Data.IsLessThan(currentNode.Data))
{
var temp = nextNode.Data;
nextNode.Data = currentNode.Data;
currentNode.Data = temp;
}
nextNode = nextNode.Next;
}
currentNode = currentNode.Next;
}
}
/// <summary>
/// Return an array version of this list.
/// </summary>
/// <returns></returns>
public virtual T[] ToArray()
{
T[] array = new T[Count];
var currentNode = _firstNode;
for (int i = 0; i < Count; ++i)
{
if (currentNode != null)
{
array[i] = currentNode.Data;
currentNode = currentNode.Next;
}
else
{
break;
}
}
return array;
}
/// <summary>
/// Returns a System.List version of this DLList instace.
/// </summary>
/// <returns>System.List of elements</returns>
public virtual List<T> ToList()
{
List<T> list = new List<T>(Count);
var currentNode = _firstNode;
for (int i = 0; i < Count; ++i)
{
if (currentNode != null)
{
list.Add(currentNode.Data);
currentNode = currentNode.Next;
}
else
{
break;
}
}
return list;
}
/// <summary>
/// Returns the list items as a readable multi--line string.
/// </summary>
/// <returns></returns>
public virtual string ToReadable()
{
string listAsString = string.Empty;
int i = 0;
var currentNode = _firstNode;
while (currentNode != null)
{
listAsString = String.Format("{0}[{1}] => {2}\r\n", listAsString, i, currentNode.Data);
currentNode = currentNode.Next;
++i;
}
return listAsString;
}
/********************************************************************************/
public IEnumerator<T> GetEnumerator()
{
var node = _firstNode;
while (node != null)
{
yield return node.Data;
node = node.Next;
}
// Alternative: IEnumerator class instance
// return new DLinkedListEnumerator(this);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
// Alternative: IEnumerator class instance
// return new DLinkedListEnumerator(this);
}
/********************************************************************************/
internal class DLinkedListEnumerator : IEnumerator<T>
{
private DLinkedListNode<T> _current;
private DLinkedList<T> _doublyLinkedList;
public DLinkedListEnumerator(DLinkedList<T> list)
{
this._current = list.Head;
this._doublyLinkedList = list;
}
public T Current
{
get { return this._current.Data; }
}
object System.Collections.IEnumerator.Current
{
get { return Current; }
}
public bool MoveNext()
{
if (_current.Next != null)
_current = _current.Next;
else
return false;
return true;
}
public bool MovePrevious()
{
if (_current.Previous != null)
_current = _current.Previous;
else
return false;
return true;
}
public void Reset()
{
_current = _doublyLinkedList.Head;
}
public void Dispose()
{
_current = null;
_doublyLinkedList = null;
}
}
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C#
1
https://gitee.com/strongandyzhang/C-Sharp-Algorithms.git
git@gitee.com:strongandyzhang/C-Sharp-Algorithms.git
strongandyzhang
C-Sharp-Algorithms
C-Sharp-Algorithms
master

搜索帮助