简体   繁体   English

创建链接列表。 C#

[英]Creating A Linked List. C#

I've tried creating linked list/node classes and I'm not sure where to go next.我已经尝试创建链表/节点类,但我不确定接下来在哪里 go。 My attempts haven't went well because after creating the classes I'm just not sure what the next step is.我的尝试并不顺利,因为在创建类之后我只是不确定下一步是什么。

I'm trying to create a program that has a dinosaur node which saves information about the dinosaur such as id, species etc and I want to allow the user to create and remove dinosaurs from the list.我正在尝试创建一个具有恐龙节点的程序,该节点保存有关恐龙的信息,例如 id、物种等,并且我希望允许用户从列表中创建和删除恐龙。 So I need to allow the user to input data, I assume there's a way to make dino id get set automatically but I'm not to sure.所以我需要允许用户输入数据,我假设有一种方法可以让恐龙 id 自动设置,但我不确定。

I've included the LinkedList.cs and the Node.cs so you can see where I'm going but I have no idea what to do within my program class to utilise the linked list and achieve what I'm trying to do.我已经包含了LinkedList.csNode.cs ,所以你可以看到我要去哪里,但我不知道在我的程序 class 中做什么来利用链接列表并实现我想要做的事情。

Added Program.cs class incase that helps identify/show where I am within the program/what I need to do.添加了Program.cs class 以帮助识别/显示我在程序中的位置/我需要做什么。

Linked List Class:链表 Class:

using System;
using System.Collections.Generic;
using System.Runtime.ExceptionServices;
using System.Text;

namespace JurrasicFinal
{
    public class LinkedList
    {

        private Node head;
        private int count;

        public LinkedList()
        {
            this.head = null;
            this.count = 0;
        }

        public bool Empty
        {
            get { return this.count == 0; }
        }

        public int Count
        {
            get { return this.count; }
        }

        public object this[int index]
        {
            get { return this.Get(index); }
        }

        public object Add(int index, object o)
        {
            if (index < 0)
                throw new ArgumentOutOfRangeException("Index: " + index);

            if (index > count)
                index = count;

            Node current = this.head;

            if (this.Empty || index == 0)
            {
                this.head = new Node(o, this.head);
            }
            else
            {
                for (int i = 0; i < index - 1; i++)
                {
                    current = current.Next;
                    current.Next = new Node(o, current.Next);
                }
            }
            count++;
            return o;
        }

        public object Add(object o)
        {
            return this.Add(count, o);
        }

        public object Remove(int index)
        {
            if (index < 0)
                throw new ArgumentOutOfRangeException("Index: " + index);

            if (this.Empty)
                return null;

            if (index >= this.count)
                index = count - 1;

            Node current = this.head;
            object result = null;

            if (index == 0)
            {
                result = current.Data;
                this.head = current.Next;
            }
            else
            {
                for (int i = 0; index < index - 1; i++) ;
                current = current.Next;

                result = current.Next.Data;
                current.Next = current.Next.Next;
            }

            count--;

            return result;

        }

        public void Clear()
        {
            this.head = null;
            this.count = 0;
        }

        public int IndexOf(object o)
        {
            Node current = this.head;

            for (int i = 0; i < this.count; i++)
            {
                if (current.Data.Equals(o))
                    return i;

                current = current.Next;
            }
            return -1;
        }

        public bool Contains(object o)
        {
            return this.IndexOf(o) >= 0;
        }

        public object Get(int index)
        {
            if (index < 0)
                throw new ArgumentOutOfRangeException("Index: " + index);

            if (this.Empty)
                return null;

            if (index >= this.count)
                index = this.count - 1;

            Node current = this.head;

            for (int i = 0; i < index; i++)
                current = current.Next;

            return current.Data;
        }
    }
}

Node Class:节点 Class:

using System;
using System.Collections.Generic;
using System.Text;

namespace JurrasicFinal
{
    public class Node
    {
        private object data;
        private Node next;
    private string DinoSpecies;
    private string DinoName;

        public Node(object data, Node next)
        {
            this.data = data;
            this.next = next;
        }

        public object Data
        {
            get { return this.data; }
            set { this.data = value; }
        }

        public Node Next
        {
            get { return this.next; }
            set { this.next = value; }
        }

    }
}

Program Class:程序 Class:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq.Expressions;

namespace JurrasicFinal
{
    class Program
    {

        class Dinosaur
        {
            public string Name;
            public string Classification;
            public char Sex;
        }


        static void Main(string[] args)
        {
            LinkedList<Dinosaur> DinoList = new LinkedList<Dinosaur>();

            Dinosaur Dino1 = new Dinosaur();
            Dino1.Name = "Tyrannosaurus Rex";
            Dino1.Classification = "Carnivorous";
            Dino1.Sex = 'M';

            Dinosaur Dino2 = new Dinosaur();
            Dino2.Name = "Velociraptor";
            Dino2.Classification = "Carnivorous";
            Dino2.Sex = 'F';

            Dinosaur Dino3 = new Dinosaur();
            Dino3.Name = "Procompsognathus";
            Dino3.Classification = "Carnivorous";
            Dino3.Sex = 'M';

            void printList()
            {
                Console.WriteLine("Current Queue: ");
                Console.WriteLine("\n");
                foreach (Dinosaur d in DinoList)
                {
                    Console.WriteLine("Name: " + d.Name);
                    Console.WriteLine("Classification: " + d.Classification);
                    Console.WriteLine("Sex " + d.Sex);
                    Console.WriteLine("\n");
                }

                Console.WriteLine(Dino1.Name +  Dino1.Sex);
            }
            DinoList.AddLast(Dino1);
            DinoList.AddLast(Dino2);
            DinoList.AddLast(Dino3);
            printList();
            Console.WriteLine(DinoList.Count);


            FileStream fileStream = File.OpenWrite("E:/Work/Dinosaur.txt");
            BinaryWriter writer = new BinaryWriter(fileStream);
            foreach (Dinosaur d in DinoList)
            {
                writer.Write(d.Name);
                writer.Write(d.Classification);
                writer.Write(d.Sex);
            }
            writer.Close();


            Console.WriteLine("Reading Back From File");
            FileStream file = File.OpenRead("E:/Work/Dinosaur.txt");
            BinaryReader reader = new BinaryReader(file);
            for (int i = 1; i < 3; i++)
            {
                Dinosaur d = new Dinosaur();
                d.Name = reader.ReadString();
                d.Classification = reader.ReadString();
                d.Sex = reader.ReadChar();
                DinoList.AddLast(d);
            }
            reader.Close();
            Console.ReadKey();
        }

    }
}

I think you might be looking for something like this, which hangs on user input and tries to do simple validation.我认为您可能正在寻找类似的东西,它依赖于用户输入并尝试进行简单的验证。 I made it a bit overly complex to demonstrate some options.我让演示一些选项变得有点过于复杂。

class Sample
{
    private static int index = 0;

    static void Main(string[] args)
    {
        LinkedList<Dinosaur> DinoList = new LinkedList<Dinosaur>();

        while (true)
        {
            var dino = new Dinosaur();
            dino.Name = GetInput("Enter dino name (q to quit): ");
            if (dino.Name == "q" || dino.Name == "Q")
            {
                break;
            }

            dino.Classification = GetInput("Enter dino classification: ");
            char[] sexes = new char[] {'F', 'f', 'M', 'm'};
            while (true)
            {
                Console.WriteLine("Enter dino sex (M/F): ");
                dino.Sex = (char) Console.Read();
                if (sexes.Contains(dino.Sex))
                {
                    break;
                }
            }

            int inputIndex = default;
            while (true)
            {
                var indexString = GetInput($"Enter 0-index list position (max {DinoList.Count})");
                inputIndex = Convert.ToInt32(indexString);
                if (inputIndex <= DinoList.Count)
                {
                    break;
                }
            }
            DinoList.Add(inputIndex, dino);
            index++;

            Console.WriteLine("Dinosaurs:");
            Console.WriteLine(new string('-', 30));
            for (var i = 0; i < DinoList.Count; i++)
            {
                var dinosaur = (Dinosaur) DinoList.Get(i);
                Console.WriteLine("Name: " + dinosaur.Name);
                Console.WriteLine("Classification: " + dinosaur.Classification);
                Console.WriteLine("Sex: " + dinosaur.Sex);
            }
        }
    }

    private static string GetInput(string prompt)
    {
        Console.WriteLine(prompt);
        var input = Console.ReadLine();
        while (string.IsNullOrWhiteSpace(input))
        {
            input = Console.ReadLine();
        }
        return input;
    }
}

Note that you have to make your LinkedList and Node into LinkedList<T> and Node<T> but they converted directly, so it's just a bit of typing.请注意,您必须将LinkedListNode设为LinkedList<T>Node<T>但它们直接转换,因此只需输入一点。

Hope it helps!希望能帮助到你!

Edit: Add classes provided in question, modified to be generic.编辑:添加有问题提供的类,修改为通用类。

public class Node<T>
{
    private object data;
    private Node<T> next;
    private string DinoSpecies;
    private string DinoName;

    public Node(object data, Node<T> next)
    {
        this.data = data;
        this.next = next;
    }

    public object Data
    {
        get { return this.data; }
        set { this.data = value; }
    }

    public Node<T> Next
    {
        get { return this.next; }
        set { this.next = value; }
    }
}

public class LinkedList<T>
{
    private Node<T> head;
    private int count;

    public LinkedList()
    {
        this.head = null;
        this.count = 0;
    }

    public bool Empty
    {
        get { return this.count == 0; }
    }

    public int Count
    {
        get { return this.count; }
    }

    public object this[int index]
    {
        get { return this.Get(index); }
    }

    public object Add(int index, object o)
    {
        if (index < 0)
            throw new ArgumentOutOfRangeException("Index: " + index);
        if (index > count)
            index = count;
        Node<T> current = this.head;
        if (this.Empty || index == 0)
        {
            this.head = new Node<T>(o, this.head);
        }
        else
        {
            for (int i = 0; i < index - 1; i++)
            {
                current = current.Next;
                current.Next = new Node<T>(o, current.Next);
            }
        }
        count++;
        return o;
    }

    public object Add(object o)
    {
        return this.Add(count, o);
    }

    public object Remove(int index)
    {
        if (index < 0)
            throw new ArgumentOutOfRangeException("Index: " + index);
        if (this.Empty)
            return null;
        if (index >= this.count)
            index = count - 1;
        Node<T> current = this.head;
        object result = null;
        if (index == 0)
        {
            result = current.Data;
            this.head = current.Next;
        }
        else
        {
            for (int i = 0; index < index - 1; i++) ;
            current = current.Next;
            result = current.Next.Data;
            current.Next = current.Next.Next;
        }
        count--;
        return result;
    }

    public void Clear()
    {
        this.head = null;
        this.count = 0;
    }

    public int IndexOf(object o)
    {
        Node<T> current = this.head;
        for (int i = 0; i < this.count; i++)
        {
            if (current.Data.Equals(o))
                return i;
            current = current.Next;
        }
        return -1;
    }

    public bool Contains(object o)
    {
        return this.IndexOf(o) >= 0;
    }

    public object Get(int index)
    {
        if (index < 0)
            throw new ArgumentOutOfRangeException("Index: " + index);
        if (this.Empty)
            return null;
        if (index >= this.count)
            index = this.count - 1;
        Node<T> current = this.head;
        for (int i = 0; i < index; i++)
            current = current.Next;
        return current.Data;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM