private static SinglyNode <int> InternalMerge(SinglyNode <int> left, SinglyNode <int> right) { if (left == null) { return(right); } if (right == null) { return(left); } SinglyNode <int> node; if (left.Item > right.Item) { node = right; node.Next = InternalMerge(left, right.Next); } else { node = left; node.Next = InternalMerge(left.Next, right); } return(node); }
private static SinglyNode <T> InternalMiddleNode <T>(this SinglyNode <T> head) { if (head == null) { Throw.ArgumentNullException(nameof(head)); } if (head.Next == null || head.Next.Next == null) // when list has 1 or 2 nodes only. { return(head); } var hare = head; var tortoise = head; while (hare != null) { hare = hare.Next; if (hare == null) { break; } hare = hare.Next; tortoise = tortoise.Next; } return(tortoise); }
/// <summary> /// Удаляет первое вхождение указанного объекта из односвязного списка <see cref="SinglyLinkedList{T}"/>. /// </summary> /// <param name="item">Объект, который необходимо удалить из односвязного списка <see cref="SinglyLinkedList{T}"/>. Для ссылочных типов допускается значение <see cref="null"/>.</param> /// <returns>Значение <see cref="true"/>, если элемент <paramref name="item"/> успешно удален, в противном случае — значение <see cref="false"/>. Этот метод также возвращает <see cref="false"/>, если элемент <paramref name="item"/> не найден в односвязном списке <see cref="SinglyLinkedList{T}"/>.</returns> public bool Remove(T item) { var result = false; if (_head == null) { return(result); } SinglyNode current = _head; if (current.Value.Equals(item)) { _head = current.Next; result = true; count--; } else { while (current.Next != null && !current.Next.Value.Equals(item)) { current = current.Next; } current.Next = current.Next.Next; result = true; count--; } return(result); }
public static void Reverse <T>(this Singly <T> list) { if (list.IsEmpty) { return; } if (list.Head.Next == null) { return; } SinglyNode <T> prev = null, current = list.Head, next = list.Head.Next; list.Tail = list.Head; while (next != null) { current.Next = prev; prev = current; current = next; next = current.Next; } current.Next = prev; prev = current; list.Head = prev; }
public void Push(T item) { SinglyNode <T> newNode = new SinglyNode <T>(item); newNode.Next = top; top = newNode; count++; }
/// <summary> /// Перемещает перечислитель к следующему элементу односвязного списка <see cref="SinglyLinkedList{T}"/>. /// </summary> /// <returns>Значение <see cref="true"/>, если перечислитель был успешно перемещен к следующему элементу; значение <see cref="false"/>, если перечислитель достиг конца односвязного списка.</returns> public bool MoveNext() { _currentNode = _nextNode; if (_currentNode == null) { return(false); } _nextNode = _nextNode.Next; return(true); }
/// <summary> /// Определяет, входит ли элемент в односвязный список <see cref="SinglyLinkedList{T}"/>. /// </summary> /// <param name="item">Объект для поиска в <see cref="SinglyLinkedList{T}"/>. Для ссылочных типов допускается значение <see cref="null"/>.</param> /// <returns>Значение <see cref="true"/>, если параметр <paramref name="item"/> найден в односвязном списке <see cref="SinglyLinkedList{T}"/>; в противном случае — значение <see cref="false"/>.</returns> public bool Contains(T item) { SinglyNode current = _head; while (current != null && !current.Value.Equals(item)) { current = current.Next; } return(current != null); }
IEnumerator <T> IEnumerable <T> .GetEnumerator() { SinglyNode <T> current = head; while (current != null) { yield return(current.Value); current = current.Next; } }
public static ISinglyLinkedList <T> CreateSinglyLinkedList <T>(IEnumerable <T> collection) { var linkedList = new SinglyLinkedList <T>(); // add in linked list foreach (var item in collection) { var node = new SinglyNode <T>(item); linkedList.AddAtEnd(node); } return(linkedList); }
public bool Remove(T element) { var result = false; //check to see if list is empty var isEmpty = IsEmpty(); //only delete if list is not empty if (!isEmpty) { //one element in the list clear the contents of the list if (Head.Next == null) { Clear(); result = true; } //second element becomes head decrease the size else if (Head.Data.Equals(element)) { Head = Head.Next; CurrentSize--; result = true; } // find the previous node before the element to be remove else { var previousNode = FindPreviousNode(element); //previous node is found if (previousNode != null) { if (previousNode.Next != null) { previousNode.Next = previousNode.Next.Next; } else { previousNode.Next = null; } CurrentSize--; result = true; } } } return(result); }
public T Pop() { if (IsEmpty) { throw new InvalidOperationException("Stack is empty"); } SinglyNode <T> poppedItem = top; top = top.Next; count--; return(poppedItem.Value); }
public T Dequeue() { if (count == 0) { throw new InvalidOperationException("Queue is empty"); } T dequeued = head.Value; head = head.Next; count--; return(dequeued); }
public bool Contains(T value) { SinglyNode <T> current = head; while (current != null) { if (current.Value.Equals(value)) { return(true); } current = current.Next; } return(false); }
private SinglyNode <T> FindPreviousNode(T element) { SinglyNode <T> previousNode = null; //pointer to the head var temp = Head; while (temp.Next != null && !(temp.Data.Equals(element))) { previousNode = temp; temp = temp.Next; } return(previousNode); }
/// <summary> /// 入队 /// </summary> /// <param name="elem"></param> public void EnQueue(T elem) { SinglyNode <T> temp = new SinglyNode <T>(elem); if (IsEmpty()) { front = temp; rear = temp; } else { rear.Next = temp; rear = temp; } ++size; }
public void Add(T value) { SinglyNode <T> newNode = new SinglyNode <T>(value); if (head == null) { head = newNode; tail = newNode; tail.Next = head; } else { newNode.Next = head; tail.Next = newNode; tail = newNode; } count++; }
public void Enqueue(T value) { SinglyNode <T> newNode = new SinglyNode <T>(value); SinglyNode <T> oldTail = tail; tail = newNode; if (count == 0) { head = tail; } else { oldTail.Next = tail; } count++; }
public bool Remove(T value) { SinglyNode <T> current = head; SinglyNode <T> previous = null; if (IsEmpty) { return(false); } do { if (current.Value.Equals(value)) { if (previous != null) // if removing node is not the first { previous.Next = current.Next; if (current == tail) { tail = previous; } } else // if the first node is removing { if (count == 1) { head = tail = null; } else { head = current.Next; tail.Next = current.Next; } } count--; return(true); } previous = current; current = current.Next; }while (current != head); return(false); }
/// <summary> /// Добавляет объект в конец односвязного списка <see cref="SinglyLinkedList{T}"/>. /// </summary> /// <param name="item">Объект, добавляемый в конец односвязного списка <see cref="SinglyLinkedList{T}"/>. Для ссылочных типов допускается значение <see cref="null"/>.</param> public void Add(T item) { SinglyNode itemNode = new SinglyNode(item); if (_head == null) { _head = itemNode; } else { SinglyNode current = _head; while (current.Next != null) { current = current.Next; } current.Next = itemNode; } count++; }
/// <summary> /// AddTwoNumbersContainedInLinkedLists /// /// Question: You are given two non-empty linked lists representing /// two non-negative integers. The digits are stored in reverse order /// and each of their nodes contain a single digit. Add the two /// numbers and return it as a linked list. /// You may assume the two numbers do not contain any leading zero, except the number 0 itself. /// /// LeetCode Question /// https://leetcode.com/problems/add-two-numbers/ /// Type: LinkedList /// Difficulty: Medium /// </summary> public void AddTwoNumbersContainedInLinkedLists() { var l1 = LLUtility.CreateSinglyLinkedList(new int[] { 2, 4, 3 }).Head; var l2 = LLUtility.CreateSinglyLinkedList(new int[] { 5, 6, 4 }).Head; // Initialise it with 0 so we don't have to make flags for checking and iteration. // We'll just provide the output with next node instead. var sum = new SinglyNode <int>(0); int temp, q; temp = q = 0; ISinglyNode <int> sumPointer = sum; // checking the pointer with current digits. If both of them are null means numbers are finished. while (l1 != null || l2 != null) { // scan for nullables because numbers may not be of same length. If they aren't, // and one number finishes early then just replace it with 0 and don't hamper the addition temp = (l1?.Value ?? 0) + (l2?.Value ?? 0) + q; q = temp / 10; // carry sumPointer.Next = new SinglyNode <int>(temp % 10); // remainder goes as new node (actually sum of the nums) sumPointer = sumPointer.Next; // move it ahead to store the next remainder in the next iteration // move the pointer to next digits. Nullable is used since both the numbers may not be of same length. l1 = l1?.Next; l2 = l2?.Next; } // accomodate quotient/carry if it spills over. E.g. 11 > 1 1 if (q > 0) { sumPointer.Next = new SinglyNode <int>(q); } //Return or Print the sum now.. var list = new SinglyLinkedList <int>(); list.Head = sum.Next; list.Print(); }
/// <summary> /// 出队 /// </summary> /// <returns></returns> public T DeQueue() { if (IsEmpty()) { return(default(T)); } SinglyNode <T> p = front; front = front.Next; if (front == null) { rear = null; } --size; return(p.Data); }
private static SinglyNode <int> InternalMergeSort(this SinglyNode <int> node) { if (node == null) { Throw.ArgumentNullException(nameof(node)); } if (node.Next == null) { return(node); } var middle = node.InternalMiddleNode(); var secondHalf = middle.Next; middle.Next = null; var left = InternalMergeSort(node); var right = InternalMergeSort(secondHalf); return(InternalMerge(left, right)); }
/// <summary> /// Internal method to find and return a reference to a node in the list /// </summary> /// <param name="element">The element to be found</param> /// <returns>the reference to the node if found null otherwise</returns> private SinglyNode <T> FindNode(T element) { //create a node to store the found node SinglyNode <T> foundNode = null; //pointer to the head var temp = Head; while (temp != null) { if (temp.Data.Equals(element)) { foundNode = temp; break; } temp = temp.Next; } return(foundNode); }
/// <summary> /// Вставляет элемент в односвязный список <see cref="SinglyLinkedList{T}"/> после элемента, удовлетворяющего условиям указанного предиката. /// </summary> /// <param name="predicate">Делегат <see cref="Predicate{T}"/>, определяющий условия поиска элемента.</param> /// <param name="item">Вставляемый объект. Для ссылочных типов допускается значение <see cref="null"/>.</param> /// <returns>Значение <see cref="true"/>, если элемент <paramref name="item"/> успешно вставлен, в противном случае — значение <see cref="false"/>. Этот метод также возвращает <see cref="false"/>, если элемент, удовлетворяющий условиям указанного предиката <paramref name="predicate"/>, не найден в односвязном списке <see cref="SinglyLinkedList{T}"/>.</returns> /// <exception cref="ArgumentNullException">Свойство <paramref name="predicate"/> имеет значение <see cref="null"/>.</exception> public bool Insert(Predicate <T> predicate, T item) { if (predicate == null) { throw new ArgumentNullException(nameof(predicate)); } SinglyNode current = _head; while (current != null && !predicate(current.Value)) { current = current.Next; } if (current == null) { return(false); } current.Next = new SinglyNode(item) { Next = current.Next }; count++; return(true); }
/// <summary> /// 清空队列 /// </summary> public void Clear() { front = rear = null; size = 0; }
/// <summary> /// 初始化为空的<seealso cref="Td.Queue.CircularSequenceQueue<typeparamref name="T"/>"/> 类的新实例。 /// </summary> public LinkQueue() { front = rear = null; size = 0; }
/// <summary> /// Освобождает все ресурсы, занятые модулем <see cref="SinglyEnumerator"/>. /// </summary> public void Dispose() { _list = null; _currentNode = _nextNode = null; }
public void Clear() { head = null; tail = null; count = 0; }
public void Clear() { Head = null; CurrentSize = 0; }
/// <summary> /// Default Constructor /// </summary> public SinglyLinkedList() { Head = null; CurrentSize = 0; }