Как получить доступ к различным элементам каждого узла в связанном списке - PullRequest
0 голосов
/ 25 марта 2019

У меня есть связанный список из n узлов, каждый из которых содержит более одного элемента.Я пытаюсь написать метод, который позволяет мне искать узел, и другой метод, который позволяет мне искать элемент внутри узла.Я не могу понять, как я должен получить доступ к внутренним элементам узлов связанного списка.Итак, я думаю, что я действительно хочу знать, это то, как вы ссылаетесь / получаете доступ к каждому отдельному элементу с узлом связного списка?

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

    package nodelist;

    public class NodeList {

public int nodeid;
public int nodestate;
public int x_cord;
public int y_cord;
public int direction;

public NodeList next;

public NodeList(int nodeid, int nodestate, int x_cord, int y_cord, int direction){
    this.nodeid = nodeid;
    this.nodestate = nodestate;
    this.x_cord = x_cord;
    this.y_cord = y_cord;
    this.direction = direction;
}

public void display(){
    System.out.println("nodeid: "+nodeid + " state: " +nodestate+ " x: " +x_cord+ " y: " +y_cord+ " direction: " +direction);
}

//@Override
public String toString(){     
    return String.valueOf(this.nodeid); // Needed to convert int nodeid to string for printing
}

public static void main(String[] args) {
    // TODO code application logic here
    LinkList theLinkedList = new LinkList();

        // Insert Link and add a reference to the book Link added just prior
        // to the field next
        System.out.println("Enter the number of nodes to deploy");
                    int nodecount = 5;
                    int nodeid = 5000;
                    for(int i=0; i<nodecount;i++){
                        theLinkedList.insertFirstLink(nodeid, 0,0,0,0);

                        nodeid++;
                    }
                    /*
        theLinkedList.insertFirstLink("5000", 0,0,0,0);
        theLinkedList.insertFirstLink("5001", 1,1,1,1);
        theLinkedList.insertFirstLink("5002", 2,2,2,2);
        theLinkedList.insertFirstLink("5003", 3,3,3,3);
        */
        theLinkedList.display();

        System.out.println("Value of first in LinkedList " + theLinkedList.firstLink + "\n");

        // Removes the last Link entered

        theLinkedList.removeFirst();

        theLinkedList.display();

        //System.out.println(theLinkedList.find("The Lord of the Rings").bookName + " Was Found");

        //theLinkedList.removeNodeList("A Tale of Two Cities");

        System.out.println("\nA Tale of Two Cities Removed\n");

        theLinkedList.display();

}

    }

    public class LinkList {
// Reference to first Link in list
    // The last Link added to the LinkedList

    public NodeList firstLink; 

    LinkList(){

        // Here to show the first Link always starts as null

        firstLink = null;

    }

    // Returns true if LinkList is empty

    public boolean isEmpty(){

        return(firstLink == null);

    }

    public void insertFirstLink(int nodeid, int nodestate, int x_cord, int y_cord, int direction){

        NodeList newLink = new NodeList(nodeid, nodestate, x_cord, y_cord, direction);

        // Connects the firstLink field to the new Link 

        newLink.next = firstLink;

        firstLink = newLink;

    }

    public NodeList removeFirst(){

        NodeList linkReference = firstLink;

        if(!isEmpty()){

            // Removes the Link from the List

            firstLink = firstLink.next;

        } else {

            System.out.println("Empty LinkedList");

        }

        return linkReference;

    }

            public NodeList removeNodeList(){

        NodeList linkReference = firstLink;

        if(!isEmpty()){

            // Removes the Link from the List

            firstLink = firstLink.next;

        } else {

            System.out.println("Empty LinkedList");

        }

        return linkReference;

    }

    public void display(){

        NodeList theLink = firstLink;

        // Start at the reference stored in firstLink and
        // keep getting the references stored in next for
        // every Link until next returns null

        while(theLink != null){

            theLink.display();

            System.out.println("Next Link: " + theLink.next);

            theLink = theLink.next;

            System.out.println();

        }
      }
    }

Ответы [ 2 ]

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

Просто вы можете сделать это.Укажите временный узел на главном узле, а затем итерируйте темп.

System.out.println(temp.your_element_name);
0 голосов
/ 25 марта 2019

Вы можете сделать это, только если у вас есть одинаковое количество элементов в списке узла. В качестве отдельного узла используется структура, которая объявляется только один раз, поэтому ее память уже определена. Таким образом, вы не можете увеличить размер узла во время выполнения. Ниже я упомянул код C ++.

struct Node{
int list[5];
Node *node;
}
...