Hello! How can I write a method that would remove the elements of a doubly linked list that are in odd positions. The class method interests.
I wrote a certain solution: I created a new list, added elements that are in even positions; cleared the list for which the method was called; elements from the new list are added to the same list.
public void RemoveAtOddPosition() { LinkedList<T> newList = new LinkedList<T>(); for (int i = 0; i < Count(); i++) { if (i % 2 == 0) { newList.Add(this[i]); } } Clear(); for (int i = 0; i < newList.Count(); i++) { Add(newList[i]); } } But can there be any correct solution using links to the previous and next elements?
Class node
public class Node<T> { public T Data { get; set; } public Node<T> Previous { get; set; } public Node<T> Next { get; set; } public Node(T data) { Data = data; } } LinkedList class
public class LinkedList<T> { Node<T> head; Node<T> tail; int count; public bool IsEmpty() { return count == 0; } public int Count() { return count; } public T this[int index] { get { if (index < 0) throw new ArgumentOutOfRangeException(); Node<T> current = head; for (int i = 0; i < index; i++) { if (current.Next == null) throw new ArgumentOutOfRangeException(); current = current.Next; } return current.Data; } } public void Show() { Console.WriteLine("Двунаправленный список"); Node<T> tmp = head; while (tmp != null) { Console.Write(tmp.Data + " "); tmp = tmp.Next; } Console.WriteLine(); } public void Clear() { head = tail = null; count = 0; } public void Add(T data) { Node<T> node = new Node<T>(data); if (head == null) { head = node; } else { tail.Next = node; node.Previous = tail; } tail = node; count++; } public void RemoveAtOddPosition() { LinkedList<T> newList = new LinkedList<T>(); for (int i = 0; i < Count(); i++) { if (i % 2 == 0) { newList.Add(this[i]); } } Clear(); for (int i = 0; i < newList.Count(); i++) { Add(newList[i]); } } }
Previous/Nextelements in even positions, without constantly obtaining elements by index, which in this case is an expensive operation. - IgorLinkedList<T>class yours? - IgorHeadandTailproperties out fromLinkedList<T>? - Igor