@marlaaa

Мне надо поменять элементы местами в двусвязном списке, обмен не происходит, что я делаю не так?

Суть задания поменять местами четные элементы двусв.списка с нечетными рядом стоящими. В методе OddEven1 класса Program обмена не происходит. Предполагаю что проблема где-то в создании самого списка, так как когда я делала тоже самое для обычного List всё работало как надо.

класс Program
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OOPLaba5
{
    class Program
    {
        static void Main() { 
                                                                                                                                                                    
            string FileName = "Input.txt";
            string FileName2 = "Output.txt";
            List2<int> list = new List2<int>();
            Console.WriteLine("Введите количество элементов:");
            int size=Convert.ToInt32(Console.ReadLine());
            //ListAdd(list, size);
            FileWork fileWork = new FileWork(list, size);
            fileWork.CreateFileList(list,FileName);
            List2<int> list2 = new List2<int>();
            
            fileWork.ReadFileList(list2,FileName,list);
            OddEven1(list2);
            fileWork.CreateFileList1(list2 ,FileName2);
                       
        }
        static public void ListAdd(List2<int> num, int size)
        {
            for (int i = 0; i < size; i++)
            {
                num.Add(i);
            }
        }
        static void OddEven1(List2<int> numbers) 
        {
            for (int i = 0; i < numbers.Count; i++)
            {
                if (numbers[i] % 2 == 0)
                {
                    if (i + 1 < numbers.Count())
                    {
                        if (numbers[i + 1] % 2 != 0)
                        {
                            int tmp = numbers[i];
                            numbers[i] = numbers[i + 1];
                            numbers[i + 1] = tmp;
                        }
                    }
                }
                else
                {
                    if (i + 1 < numbers.Count())
                    {
                        if (numbers[i + 1] % 2 == 0)
                        {
                            int tmp = numbers[i];
                            numbers[i] = numbers[i + 1];
                            numbers[i + 1] = tmp;
                        }
                    }
                }
                
            }
        }
    }
}

классы двусв.списка и узла двусв.списка
using System;
using System.Collections.Generic;
using System.Collections;

namespace OOPLaba5
{
    internal class List2<T> : IEnumerable<T> 
        
    {
        NodeList<T> Head { get; set; }
        NodeList<T> Tail { get; set; }
        int Counter { get; set; }
        public T this[int index]
        {
            get
            {
                if (index < 0) throw new ArgumentOutOfRangeException();
                NodeList<T> current = Head;
                for (int i = 0; i < index; i++)
                {
                    if (current.Next == null)
                        throw new ArgumentOutOfRangeException();
                    current = current.Next;
                }
                return current.Data;
            }
            set
            {
                if (index < 0) throw new ArgumentOutOfRangeException();
                NodeList<T> current = Head;
                for (int i = 0; i < index; i++)
                {
                    if (current.Next == null)
                        throw new ArgumentOutOfRangeException();
                    current = current.Next;
                }
                return;
            }
        }
        public List2()
        {
            
        }
        public List2(T data)
        {
            var item = new NodeList<T>(data);
            Head = item;
            Tail = item;
            Counter = 1;
        }
        public void Add(T data)
        {
            var node = new NodeList<T>(data);

            if (Head == null)
                Head = node;
            else
            {
                Tail.Next = node;
                node.Prev = Tail;
            }
            Tail = node;
            Counter++;
        }
        public void AddFirst(T data)
        {
            NodeList<T> node = new NodeList<T>(data);
            NodeList<T> temp = Head;
            node.Next = temp;
            Head = node;
            if (Counter == 0)
                Tail = Head;
            else
                temp.Prev = node;
            Counter++;
        }
        public void Remove(T data)
        {
            var current = Head;
            while (current != null)
            {
                if (current.Data.Equals(data))
                {
                    current.Prev.Next = current.Next;
                    current.Next.Prev = current.Prev;
                    Counter--;
                    return;
                }
                current= current.Next;
            }            
        }

        
            public int Count { get { return this.Counter; } }
           
        IEnumerator IEnumerable.GetEnumerator()
            {
                return ((IEnumerable)this).GetEnumerator();
            }

            IEnumerator<T> IEnumerable<T>.GetEnumerator()
            {
                var current = Head;
                while (current != null)
                {
                    yield return current.Data;
                    current = current.Next;
                }
            }

            public IEnumerable<T> BackEnumerator()
            {
                var current = Tail;
                while (current != null)
                {
                    yield return current.Data;
                    current = current.Prev;
                }
            }
    }
}


using System;


namespace OOPLaba5
{
    internal class NodeList<T>
    {
        public T Data { get; set; }
        public NodeList<T> Next { get; set; }
        public NodeList<T> Prev { get; set; }

        public NodeList(T Data)
        {
            this.Data = Data;
        }
    }
    
}

класс с методами записи/чтения файла
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace OOPLaba5
{
    internal class FileWork
    {
        List2<int> Numbers { get; set; }

        public FileWork(List2<int> numbers, int size)
        {
            this.Numbers = numbers;
            Random rand = new Random();
            int[] rander= new int[size];
            for (int i = 0; i < size; i++)
            {
                rander[i]= rand.Next(0, 100);
            }
            for (int i = 0; i < size; i++)
            {
                numbers.Add(rander[i]);
            }
        }


        public void CreateFileList(List2<int> Numbers, string FileName)
        {
            string str = "";

            for(int i = 0; i < Numbers.Count; i++)
            {
                str = str+Numbers[i]+" ";
            }
            File.WriteAllText(FileName, str);
        }
        public void CreateFileList1(List2<int> Numbers, string FileName)
        {
            string str = "";

            for (int i = 0; i < Numbers.Count; i++)
            {
                str = str + Numbers[i] + "\n";
            }
            File.WriteAllText(FileName, str);
        }
        public void ReadFileList(List2<int> Number, string FileName,List2<int> Number1)
        {
            string str=File.ReadAllText(FileName);
            string[] q = str.Split(' ');
            string[] arr=new string[q.Length-1];
            for(int i=0; i<q.Length-1; i++)
            {
                arr[i] = q[i];
            }
            for (int i = 0; i < Number1.Count(); i++)
            {
                Number.Add(Convert.ToInt32(arr[i]));
            }
        }
    }
}
  • Вопрос задан
  • 89 просмотров
Пригласить эксперта
Ответы на вопрос 1
Alexeytur
@Alexeytur
Что увидел на скорый глаз:

1) В сеттере индексатора класса List2 нет собственно установки нового значения,
строки вида current.Data = value;

2) Вам нужно обменять четные и нечетные элементы, то есть имеется в виду четные/нечетные индексы в списке?
А в методе OddEven1 вы работаете с четными/нечетными значениями по индексам.
Тогда в этом методе нужно сравнения вида numbers[i] % 2 заменить на i % 2
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы