Я пытаюсь вставить узел в связанный список в любом месте, Java - PullRequest
2 голосов
/ 07 октября 2019

Я создал 3 класса: MainClass, Node, FunctionClass;

Теперь я хочу вставить узел в любой момент, пожалуйста, дайте мне знать, что не так с моим кодом, почему он не работает, есть ли логическийerror1

в Node Class у меня есть только один выбор: добавить два конструктора, дайте мне знать, может ли помочь конструирование

public class Node {
public int data;
public Node next;
public static int count = 0;

Node(int data)
{
    this.data = data;
    next = null;
    count++;
}
Node ()
{
    this.data = 0;
    next = null;
    count++;
}}

// внутри класса функций я использовал этот метод;

    public void inssrtatAnyPoint(int data, int pos)
    {
    Node last = findNode(pos);
    if (Node.count==0) this.insert(data);
    else{
    Node temp = last;
    last = new Node(data);
    last.next = temp;
    }}
    public Node findNode(int d)        
    {
    Node found = head;
    while (found.next!=null)
    {
    if (found.data == d) break;
    found = found.next;
    }
    return found;
    }

    public void insert(int data)
    {
    if (head == null){ head = new Node(data);}
    else 
    {
    Node newnode = new Node(data);
    newnode.next = head;
    head = newnode;
    }}

// процедуры для основного класса здесь

    FunctionalClass fc = new FunctionalClass();
    fc.printList();
    fc.insert(10);
    fc.insert(20);
    fc.insert(30);
    fc.inssrtAtEnd(1);
    System.out.println("list before");
    fc.printList();
    fc.inssrtatAnyPoint(25, 20);
    System.out.println("list after");
    fc.printList();FunctionalClass fc = new FunctionalClass();
    fc.printList();
    fc.insert(10);
    fc.insert(20);
    fc.insert(30);
    fc.inssrtAtEnd(1);
    System.out.println("list before");
    fc.printList();
    fc.inssrtatAnyPoint(25, 20);
    System.out.println("list after");
    fc.printList();

1 Ответ

0 голосов
/ 07 октября 2019

Вы в порядке с вставкой после найденного узла, а не перед ним? Это можно сделать с небольшим изменением в вашем методе.

    public void insertAtAnyPoint(int data, int pos) {
        Node last = findNode(pos);
        if (Node.count == 0) this.insert(data);
        else {
            Node temp = last;
            last = new Node(data);
            last.next = temp.next;
            temp.next=last;
        }
    }

Для вставки до того, как найденному узлу понадобится findNode, чтобы вернуть предыдущий узел туда, куда вы хотите вставить его, являющийся односвязным списком.

Вставка перед положением:

    public Node findNodeToInsert(int d) {
        Node found = head;
        Node prev = null;
        while (found.next != null) {
            if (found.data == d)
            {
                break;
            }
            prev = found;
            found = found.next;
        }
        return prev;
    }

    public void insertAtAnyPoint(int data, int pos) {
        if (Node.count == 0) this.insert(data);
        else {
            Node last = findNodeToInsert(pos);
            Node temp = last;
            last = new Node(data);
            last.next = temp.next;
            temp.next=last;
        }
    }
...