Что является лучшей реализацией связанного списка?
My lecturer has this implementation of a Linked List. The data object is the representation of a boat but the data object in the structure seems tightly coupled from my pov because data object should be separate from the linked list.
class Boatnode { private string Owner; // owners name private string Boatname; // name of boat private string Boattype; //type of boat private int Boatlength; //length of boat private Boatnode next; // link to next public Boatnode(string owner , string boatname, string boattype ,int boatlength) { Owner = owner; // store name Boatname = boatname; Boattype = boattype; Boatlength = boatlength; next = null; // initialise next } public void setNext(Boatnode nextNode) { next = nextNode; // change next node } public Boatnode getNext() { return next; } public string getOwner() { return Owner; } public string getBoatName() { return Boatname; } public string getBoatType() { return Boattype; } public int getBoatLength() { return Boatlength; } } // end class TownNode
Что я уже пробовал:
I proposed this solution instead but he rejected it saying that the boat object was not properly encapsulated
public class Node { public Boat Data; public Node Next; public Node(Boat data) { Data = data; } } public class Queue { private Node _head; private Node _tail; private int _count = 0; public Queue() { } public void Enqueue(Boat data) { Node _newNode = new Node(data); if (_head == null) { _head = _newNode; _tail = _head; } else { _tail.Next = _newNode; _tail = _tail.Next; } _count++; } public Boat Dequeue() { Boat _result = new MarinaBerthClassLibrary.Boat(); if (_head == null) { throw new Exception("Queue is Empty"); } _result = _head.Data; _head = _head.Next; return _result; } public int Count { get { return this._count; } } public string PrintElements() { var node = _head; string[] elements = new string[_count]; int i = 0; if (node!=null) { while (node != null) { elements[i++] = node.Data.NameOfBoat; node = node.Next; } return string.Join(" ", elements); } return ("No Data"); } }
What would be a better implementation of this?
Richard MacCutchan
Я согласен с вами. Класс node должен иметь возможность обрабатывать любой объект, чтобы создать linkedlist. Помещение данных лодки в узел предотвращает это. Мой единственный комментарий к вашему решению заключается в том, что ваши узлы ожидают ссылки на лодку, но им было бы лучше, если бы они приняли объект. Затем вы можете использовать этот код для управления любым типом, который наследуется от объекта.