/// <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); }
public virtual DLinkedList <T> GetRange(int index, int countOfElements) { DLinkedListNode <T> currentNode = null; DLinkedList <T> newList = new DLinkedList <T>(); if (Count == 0) { return(newList); } if (index < 0 || index > Count) { throw new IndexOutOfRangeException(); } 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; } } while (currentNode != null && newList.Count <= countOfElements) { newList.Append(currentNode.Data); currentNode = currentNode.Next; } return(newList); }