Удаление узла в двусвязном списке с параметром String Key? - PullRequest
0 голосов
/ 28 октября 2018

У меня проблемы с созданием метода, который удаляет узел по параметру "ключ" строки.Мне дали строку с именем key в качестве параметра.

Итак, это мой Node.java

public class Node {
public Node next;
public Node prev;
public String data;

public void setData(String data) {
    this. data = data;
}
public String getData() {
    return this.data;
}
}

, а это мой DoubleLinkedList.java:

public class DoubleLinkedList {

public Node head;
public Node tail;
public int size;

public DoubleLinkedList() {
    this.head = head;
    this.tail = tail;
    this.size = 0;
}

public void addFirst(String data) {
    Node newNode = new Node();
    newNode.setData(data);
    if (head == null && tail == null) {
        head = newNode;
        tail = head;

    } else {
        head.prev = newNode;
        newNode.next = head;
        head = newNode;
    }
    size++;
}

public void deleteFirst() {
    if (head == tail) {
        head = null;
        tail = null;

    } else {
        head = head.next;
        head.prev = null;
    }
    size--;
}

public void deleteLast() {
    if (head == tail) {
        head = null;
        tail =null;

    } else {
        tail = tail.prev;
        tail.next =null;
    }
    size--;
}
public boolean find(String key) {
    Node temp = head;
    while (!temp.getData().equals(key)) {
        if(temp.next == null) {
            return false;
        }
        temp = temp.next;
    }
    return true;
}
public void deleteByKey(Node key) {
    /*CODE HERE



    */
}

public void display() {
    if(head != null) {
        Node temp = head;
        while (temp != null) {
            System.out.println(temp.getData()+ " ");
            temp = temp.next;
        }
    } else {
        System.out.println("Double LinkedList anda kosong!");
    }
}
public boolean isEmpty() {
    return (head == null && tail == null);
}
public void makeEmpty() {
    head = null;
    tail = null;
}




}

Я хочу удалить узел с тем же элементом, что и «ключ»:

Список (до): ABCDEFG

DeleteByKey (D);

Список (после): ABCEFG

1 Ответ

0 голосов
/ 28 октября 2018
public void deleteByKey(String key) {
    Node temp = head;
    Node temp1 = null;
     while (!temp.getData().equals(key)) {
            if(temp.next == null) {
                System.out.println("data not found");
                break;
            }
            temp1=temp;
            temp = temp.next;

        }
     if(temp.getData().equals(key)) {
         temp=temp.next;
         temp.prev=temp1;
         temp1.next=temp;


     }

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...