2014-12-10 4 views
1

Мой метод int deleteLast() должен удалить последний узел, а также вернуть значение внутри удаляемого узла. мой код, похоже, не работает. он не удаляет последний узел. Любая помощь будет оценена.удаление последнего узла из одноуровневого списка (java)

импорт java.util.NoSuchElementException; импорт java.util.Scanner;

общественного класса LinkedList11 { // Частный внутренний класс Node

private class Node{ 
    int data; 
    Node link; 


    public Node(){ 
     data = Integer.MIN_VALUE; 
     link = null; 
    } 

    public Node(int x, Node p){ 
     data = x; 
     link = p; 
    } 
} 
// End of Node class 

public Node head; 

public LinkedList11(){ 
    head = null; 
} 

public int deleteLast() throws NoSuchElementException { 


    if (head == null) //handle when list is empty 
    { throw new NoSuchElementException();} 

    if(head.link == null) //handle when head is the only node 
    { return head.data; 


     } 

     Node position = head; 
     Node temp = head; //temp has to be initialized to something 
     int dataAtEnd =0; 
     while (position != null) 
     { dataAtEnd = position.data;  
      temp =position;    //safe keep current position 
      position = position.link;  //update position pointer to get the next value 
      } 

     position =temp; // store current position in next position 
     return dataAtEnd; 

} 

}

ответ

2

сначала, если голова является единственным узлом, и вы хотите удалить его, вам нужно установить head null.

if(head.link == null) { 
    int result = head .data; 
    head = null; 
    return result; 
} 

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

Node current = head; 
while (current.link.link != null) 
    current = current.link; 
int result = current.link.data; 
current.link = null; 
return result; 

Bc вы должны смотреть на шаги вперед, чтобы проверить, если следующий узел является последним один и удалить последний из одного до последний. Надеюсь, вы понимаете, что я имел в виду и извиняюсь за опечатки

+0

Большое спасибо за объяснение. Просто протестировал его, работает. –

0

удалить линии "возврата head.data;" который находится справа, где вы получаете ошибку. "Свинец = NULL; // дает ошибка" дает недостижима, потому что у вас есть оператор возврата прямо выше, так что, очевидно, недостижимый

`общественного ИНТ deleteLast() бросает NoSuchElementException {

if (head == null) //handle when list is empty 
{ throw new NoSuchElementException();} 

if(head.link == null) //handle when head is the only node 
{ 
    // You must store the data somewhere since head has to be set to NULL. 
    int dataToReturn = head.data; 

    // Since head is the only node, set it to NULL now. 
    head = null; 

    // Now return the data the the last node (head in this case) contained. 
    return dataToReturn; 
    } 

    Node position = head; 
    Node temp = head; //temp has to be initialized to something 
    int dataAtEnd =0; 

    while (position.link != null) 
    { dataAtEnd = position.data;  
     temp =position;    //safe keep current position 
     position = position.link;  //update position pointer to get the next value 
     } 

    position = null; 
    temp.link = null;//this is what deletes the last node. 

    return dataAtEnd; 

}

+0

спасибо, но он все еще не удаляет последний узел –

+0

см. Мои правки. я не тестировал его, но он должен решить его для вас. Самое главное, что вы не устанавливали temp.link в null. – RAEC

+0

Большое спасибо за комментарии. Они помогли прояснить ситуацию. Существует только незначительная ошибка, хотя код удаляет последний узел, он не отображает правильное значение, которое удаляется. –

Смежные вопросы