Удвоение всех вхождений элементов, расположенных на четных (0-четное) позициях - C#

Узнай цену своей работы

Формулировка задачи:

Разработать два метода для класса List (однонаправленный список и двунаправленный список). Удвоение всех вхождений элементов, расположенных на четных (0-четное) позициях (DublicateOnEvenPos()). Исходник однонаправленного списка (уже начал писать этот метод, но не получается):
Листинг программы
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace Lists
  7. {
  8. class List<T>: IEnumerable<T>, IEnumerator<T>
  9. {
  10. class ListItem<T1>
  11. {
  12. public T Data { get; set; }
  13. public ListItem<T> Next { get; set; }
  14. }
  15. private ListItem<T> firstItem;
  16. private ListItem<T> currentItem;
  17. public T Current
  18. {
  19. get
  20. {
  21. if (currentItem == null)
  22. throw new NullReferenceException("Current item can't be null");
  23. return currentItem.Data;
  24. }
  25. set
  26. {
  27. if (currentItem == null)
  28. throw new NullReferenceException("Current item can't be null");
  29. currentItem.Data = value;
  30. }
  31. }
  32. public void AddFirst(T item)
  33. {
  34. ListItem<T> newItem = new ListItem<T>();
  35. newItem.Data = item;
  36. newItem.Next = firstItem;
  37. firstItem = newItem;
  38. }
  39. public IEnumerator<T> GetEnumerator()
  40. {
  41. return this;
  42. }
  43. System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
  44. {
  45. return this;
  46. }
  47. public void Dispose()
  48. {
  49. }
  50. object System.Collections.IEnumerator.Current
  51. {
  52. get
  53. {
  54. if (currentItem == null)
  55. throw new NullReferenceException("Current item can't be null");
  56. return currentItem.Data;
  57. }
  58. }
  59. public bool MoveNext()
  60. {
  61. if (currentItem == null)
  62. {
  63. if (HasValues)
  64. {
  65. currentItem = firstItem;
  66. return true;
  67. }
  68. return false;
  69. }
  70. if (currentItem.Next != null)
  71. {
  72. currentItem = currentItem.Next;
  73. return true;
  74. }
  75. Reset();
  76. return false;
  77. }
  78. public void Reset()
  79. {
  80. currentItem = null;
  81. }
  82. public bool HasValues
  83. {
  84. get { return firstItem != null; }
  85. }
  86. public void DublicateOnEvenPos()
  87. {
  88. ListItem<T> newItem = new ListItem<T>();
  89. var Count = 0; // счетчик для элементов
  90. newItem = firstItem;
  91. while (MoveNext())
  92. {
  93. if (Count % 2 == 0 || Count == 0)
  94. {
  95. newItem = currentItem;
  96. newItem.Next = currentItem.Next;
  97. currentItem.Next = newItem;
  98. }
  99. Count++;
  100. }
  101. }
  102. }
  103. }
Исходник двунаправленного списка
Листинг программы
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace ListsDemo
  7. {
  8. public class DoubleList<T> : IEnumerable<T>, IEnumerator<T>
  9. {
  10. class ListItem<T1>
  11. {
  12. public ListItem<T1> Prev { get; set; }
  13. public T1 Data { get; set; }
  14. public ListItem<T1> Next { get; set; }
  15. }
  16. private ListItem<T> firstItem;
  17. private ListItem<T> currentItem;
  18. private ListItem<T> lastItem;
  19. public T Current
  20. {
  21. get
  22. {
  23. if (currentItem == null)
  24. throw new NullReferenceException("Current item can't be null");
  25. return currentItem.Data;
  26. }
  27. set
  28. {
  29. if (currentItem == null)
  30. throw new NullReferenceException("Current item can't be null");
  31. currentItem.Data = value;
  32. }
  33. }
  34. public void AddFirst(T item)
  35. {
  36. ListItem<T> newItem = new ListItem<T>();
  37. newItem.Data = item;
  38. newItem.Next = firstItem;
  39. firstItem = newItem;
  40. if(firstItem.Next == null)
  41. {
  42. lastItem = firstItem;
  43. }
  44. else
  45. {
  46. firstItem.Next.Prev = firstItem;
  47. }
  48. }
  49. public IEnumerator<T> GetEnumerator()
  50. {
  51. return this;
  52. }
  53. System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
  54. {
  55. return this;
  56. }
  57. public void Dispose()
  58. {
  59. }
  60. object System.Collections.IEnumerator.Current
  61. {
  62. get
  63. {
  64. if (currentItem == null)
  65. throw new NullReferenceException("Current item can't be null");
  66. return currentItem.Data;
  67. }
  68. }
  69. public bool MoveNext()
  70. {
  71. if (currentItem == null)
  72. {
  73. if (HasValues)
  74. {
  75. currentItem = firstItem;
  76. return true;
  77. }
  78. return false;
  79. }
  80. if (currentItem.Next != null)
  81. {
  82. currentItem = currentItem.Next;
  83. return true;
  84. }
  85. Reset();
  86. return false;
  87. }
  88. public void Reset()
  89. {
  90. currentItem = null;
  91. }
  92. public bool HasValues
  93. {
  94. get { return firstItem != null; }
  95. }
  96. }
  97. }
Main
Листинг программы
  1. using System;
  2. using System.Linq;
  3. using System.Text;
  4. using System.Threading.Tasks;
  5. namespace Lists
  6. {
  7. class Program
  8. {
  9. static void Main(string[] args)
  10. {
  11. List<int> lst = new List<int>();
  12. lst.AddFirst(5);
  13. lst.AddFirst(4);
  14. lst.AddFirst(3);
  15. lst.AddFirst(2);
  16. lst.AddFirst(1);
  17. lst.DublicateOnEvenPos();
  18. PrintList(lst);
  19. Console.ReadLine();
  20. }
  21. private static void PrintList(List<int> lst)
  22. {
  23. Console.WriteLine("------------");
  24. foreach (var item in lst)
  25. {
  26. Console.WriteLine(item);
  27. }
  28. }
  29. }
  30. }

Решение задачи: «Удвоение всех вхождений элементов, расположенных на четных (0-четное) позициях»

textual
Листинг программы
  1.         public List<T> DublicateOnEvenPos()
  2.         {
  3.             var tmpCount = 0;
  4.             //Создаём список, с которым будем работать
  5.             List<T> tmpList = new List<T>();
  6.             //Переносимся в начало списка
  7.             currentItem = firstItem;
  8.             while (currentItem != null)
  9.             {
  10.                 if (tmpCount % 2 == 0)
  11.                 {
  12.                     tmpList.AddFirst(currentItem.Data);
  13.                     tmpList.AddFirst(currentItem.Data);
  14.                     // После этого копирования оставшиеся элементы будут стоять в обратном порядке
  15.  
  16.                 }
  17.                 else
  18.                 {
  19.                     tmpList.AddFirst(currentItem.Data);
  20.                 }
  21.                 tmpCount++;
  22.                 MoveNext();
  23.             }
  24.             // Создаем конечный список, в который скопируем элементы из предыдущего,
  25.             //чтобы восстановить порядок
  26.             List<T> list = new List<T>();
  27.             foreach (T tmp in tmpList)
  28.             {
  29.                 list.AddFirst(tmp);
  30.             }
  31.             return list;
  32.         }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

13   голосов , оценка 4.154 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы