c # связанные списки, вернуть несколько записей - PullRequest
0 голосов
/ 15 марта 2019

Я пытаюсь создать связанный список, например, с типом Bird Survey, и я пытаюсь получить конечный вывод, в котором будут возвращены все виды, которые я ввел, и сколько раз я вошел в каждый из них. Прямо сейчас вывод подсчитывает каждую отдельную птицу, которую я ввел, но он не дает отдельного подсчета в конце отчета для каждого, который я ввел, и я не уверен, как это сделать. Я возился с этим часами, я чувствую, что я очень близок, пожалуйста, помогите, если можете <3 ... Вот код: </p>

class Program
{
    public class Node
    {

        /* You add the type of bird and a count of 
         * how many times that bird is said. 
         * Then you use a method to print out 
         * the types of birds and how many times each bird was said*/
        public string bird;
        public Node next;
        public Node(string i)
        {
            bird = i;
            next = null;
        }
        public void getReport()
        {
            Console.Write("|" + bird + "|->");
            if (next != null)
            {
                next.getReport();
            }
        }
        public void AddToEnd(string bird)
        {
            if (next == null)
            {
                next = new Node(bird);
            }
            else
            {
                next.AddToEnd(bird);
            }
        }

        public class BirdList
        {
            public Node headNode;

            public BirdList()
            {
                headNode = null;
            }
            public void AddToEnd(string bird) //method to add to the end of a list 
            {
                if (headNode == null)
                {
                    headNode = new Node(bird);
                }
                else
                {
                    headNode.AddToEnd(bird);
                }
            }
            public void AddToBeginning(string bird) //add to the beginning of a list
            {
                if (headNode == null)
                {
                    headNode = new Node(bird);                      
                }
                else
                {
                    Node temp = new Node(bird);
                    temp.next = headNode;
                    headNode = temp;
                }
            }
            public void getReport()
            {
                if (headNode != null)
                {
                    headNode.getReport();
                }
            }
            public int getCount(string bird)
            {                 
                Node current = headNode;
                int count = 0;
                while (current!= null)
                {
                    if (current.bird == bird)
                    {
                        count++;
                    }
                    current = current.next; 
                }
                return count;
            }

        }
        static void Main(string[] args)
        {
            BirdList birdList = new BirdList();

            string userInput = "";
            while (userInput != "done")
            {
                Console.WriteLine("Please enter a bird:");
                userInput = Console.ReadLine();
                if (userInput == "done")
                {
                    break;
                }
                birdList.AddToEnd(userInput);
                Console.WriteLine(birdList.getCount(userInput));
            }

            birdList.getReport();
            Console.ReadLine();

И результат выглядит примерно так: image

Ответы [ 2 ]

1 голос
/ 15 марта 2019

когда вы запускаете функцию отчета, кажется, что он не имеет инструкции фактически подсчитывать количество каждого отдельного элемента, с которым он сталкивается.

Простой способ решить эту проблему - перебрать список и сохранить каждыйотдельная строка встречается в словаре, а затем увеличивается значение, когда вы обнаружите, что словарь уже содержит дубликат.

Node n = birdList.headNode;
Dictionary<string,int> dict = new Dictionary<string,int>();
while(n!=null){
    if(dict.ContainsKey(n.bird))
    {
        dict[n.bird]++;
    }else{
        dict.Add(n.bird,1);
    }
    n=n.next;
}

Диктовка должна содержать всех птиц в качестве ключа, с их суммами в качестве значений.

0 голосов
/ 15 марта 2019

Ваш код был хорош, просто не хватало нескольких вещей.Для одного каждой птице нужен счетчик.Также нет необходимости добавлять птицу снова, как только она окажется в списке.Я немного переписал ваш код и разместил комментарии, чтобы вы могли их увидеть.здесь вы идете:

class Program
    {
        public class Node
        {

            /* You add the type of bird and a count of 
             * how many times that bird is said. 
             * Then you use a method to print out 
             * the types of birds and how many times each bird was said*/
            public string bird;
            public Node next;
            public int count; // each bird needs a counter
            public Node(string i)
            {
                bird = i;
                next = null;
                count = 0;
            }
            public void getReport()
            {
                Console.Write("|" + bird + "|->" +  count );
                if (next != null)
                {
                    next.getReport();
                }
            }
            public void AddToEnd(string bird)
            {
                if (this.bird != bird) // if the bird is already in the list, it wont add it in again.
                {
                    if (next == null)
                    {
                        next = new Node(bird);
                    }
                    else
                    {
                        next.AddToEnd(bird);
                    }
                }
            }

            public class BirdList
            {
                public Node headNode;

                public BirdList()
                {
                    headNode = null;
                }
                public void AddToEnd(string bird) //method to add to the end of a list if bird is not already in the list. 
                {
                    if (headNode == null)
                    {
                        headNode = new Node(bird);
                    }
                    else
                    {
                        headNode.AddToEnd(bird);
                    }
                }
                public void AddToBeginning(string bird) //add to the beginning of a list
                {
                    if (headNode == null)
                    {
                        headNode = new Node(bird);
                    }
                    else
                    {
                        Node temp = new Node(bird);
                        temp.next = headNode;
                        headNode = temp;
                    }
                }
                public void getReport()
                {
                    if (headNode != null)
                    {
                        headNode.getReport();
                    }
                }
                public int getCount(string bird)
                {
                    Node current = headNode;
                    int count = 0;
                    while (current != null)
                    {
                        if (current.bird == bird)
                        {
                            current.count++; // once the bird is found, increment the counter.
                            count = current.count; // set the birds counter to the count.
                        }
                        current = current.next;
                    }

                    return count;
                }

            }
            static void Main(string[] args)
            {
                BirdList birdList = new BirdList();

                string userInput = "";
                while (userInput != "done")
                {
                    Console.WriteLine("Please enter a bird:");
                    userInput = Console.ReadLine();
                    if (userInput == "done")
                    {
                        break;
                    }
                    birdList.AddToEnd(userInput);
                    Console.WriteLine(birdList.getCount(userInput));
                }

                birdList.getReport();
                Console.ReadLine();
            }
        }
    }
...