Не рекурсивный метод добавления нового элемента n-ым в список - C#
Формулировка задачи:
Ничего не работает. И вообще не уверен в правильности. Не понимаю, как вставлять, вместо чего.
Листинг программы
- using System;
- namespace Лаба_2
- {
- class Program
- {
- static void Main(string[] args)
- {
- RList list = new RList(1, null);
- list = new RList(2, list);
- list = new RList(3, list);
- list.AddElByIndex(4, 4);
- do
- {
- Console.WriteLine(list.info);
- list = list.next;
- }
- while (list != null);
- }
- }
- class RList
- {
- public int info;
- public RList next;
- public RList(int i, RList n)
- {
- info = i;
- next = n;
- }
- public void AddElByIndex(int a, int index)
- {
- int count = 0;
- RList el = this;
- while (el.next != null)
- {
- count++;
- if (count == index)
- {
- el = new RList(a, null);
- break;
- }
- el = el.next;
- }
- }
- }
- }
Решение задачи: «Не рекурсивный метод добавления нового элемента n-ым в список»
textual
Листинг программы
- class Program
- {
- static void Main()
- {
- var list = new RList();
- list.Add(11);
- list.Add(13);
- list.Add(15);
- Console.Write("после add: ");
- Console.WriteLine(list);
- list.Insert(0, 10);
- list.Insert(2, 12);
- list.Insert(4, 14);
- Console.Write("после insert: ");
- Console.WriteLine(list);
- Console.ReadLine();
- }
- }
- class RListItem
- {
- public int Value;
- public RListItem Next;
- public RListItem(int Value = 0, RListItem Next = null)
- {
- this.Value = Value;
- this.Next = Next;
- }
- }
- class RList
- {
- private RListItem Root = new RListItem();
- // Добавляет в конец
- public void Add(int Value)
- {
- Insert(int.MaxValue, Value);
- }
- // Вставляет перед элементом под номером Index
- public void Insert(int Index, int Value)
- {
- var node = Root;
- while (Index-- > 0 && node.Next != null)
- node = node.Next;
- node.Next = new RListItem(Value, node.Next);
- }
- public override string ToString()
- {
- var sb = new StringBuilder();
- var node = Root.Next;
- while (node != null)
- {
- sb.Append(node.Value);
- sb.Append(" ");
- node = node.Next;
- }
- return sb.ToString();
- }
- }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д