Problem: Delete the last node of a linked list, only the first node is known.
Idea: Because only know the first node, so can only go through the linked list, find the last two nodes, the next second node is defined as NULL, the last node cannot be associated, it can be implemented. (The reason for not directly letting the last one empty is to ensure accuracy)
Code: Package chapter1.a3;
public class Example1319 {
Private class node{int item; Node Next; }
Private Node first;
private void Deletelastnode () {Node current = First, if (current = = null) return;
Node next = current. Next; If Next is empty, then only one first exists, so the direct first is empty so if (next = null) first = NULL;
while (next next! = null) {current = next; next = Next Next;}
Current. next = null; Why is it not possible to write Next = null directly here; Because next = null does not mean that current does not access the Current.next, it is still possible,//So write as Current.next = null, in order to ensure that the last node is deleted
}
}
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.