Reputation: 1079
I am reading algorithm to delete last element of a singly Linked List. Assume I have a Linked List Object called ListNode:
public class ListNode {
private int data;
private ListNode next;
public ListNode(int data) {
this.data = data;
}
public int getData() {
return this.data;
}
public void setData(int data) {
this.data = data;
}
public ListNode getNext() {
return this.next;
}
public void setNext(ListNode next) {
this.next = next;
}
}
I found the method to delete the last node of the list is:
public ListNode deleteAtTail(ListNode head) {
if (head == null || head.next == null) return null;
ListNode node = head;
while(node.next.next != null) {
node = node.next;
}
node.next = null;
return head;
}
I am confusing how this code is working since everything is through "node". However, when return head, the last node is deleted. Therefore, I wonder how it is working, is it related to "passed by value" in Java?
Upvotes: 2
Views: 9035
Reputation: 11
Since none of the answers are clear (nor correct in my opinion, because if we have node.next.next and we have only 1 element, we will get a NullPointerException), I'd like to give my two cents.
There are 3 scenarios:
So, my approach is to have an initial previous variable set as null (imagine you are before the beginning of the list). Then in the while loop, if it has 1 item, it wont execute any commands (it will skip it and prev will be null), else, go with point 3. Here's the code:
if(head == null) return;
ListNode iterator = head;
ListNode prev = null;
while(iterator.next !=null) {
prev = iterator;
iterator=iterator.next;
}
if(prev == null) head = null;
else prev.next = null;
Hope this helps.
Upvotes: 1
Reputation: 13566
You can notice that the method is iterating through all nodes till second last node because the next
of last node will be null
.
while(node.next.next != null) {
node = node.next;
}
Above code will give you second last node and its next is set to null
using node.next = null;
This means second last node will become last node now.
Upvotes: 1
Reputation: 393956
You iterate over the node
s of the list until node.next.next
is null.
At this point, node
refers to the next to last node, and node.next
refers to the last node. Setting node.next
to null removes the last node from the list, since no node in the list refers to it anymore.
Upvotes: 5