How del function is Working Especially in while condition i don't understand how it is working program to delete last node in li | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
- 1

How del function is Working Especially in while condition i don't understand how it is working program to delete last node in li

package newgf; class Node{ int data; Node next; Node(int x) { data=x; next=null; } } class newjava { public static void main(String[] args) { Node head= new Node(10); head.next = new Node(20); head.next.next = new Node(30); head.next.next.next = new Node(40); del(head); printf(head); } static Node del(Node head) { if(head==null) // return null; if(head.next==null) return null; Node curr = head; while(curr.next.next != null) curr=curr.next; curr.next=null; return head; } static void printf(Node head) { while(head!=null) { System.out.println(head.data); head=head.next; } } }

25th Jun 2021, 1:46 AM
Sachin Saxena
Sachin Saxena - avatar
3 Answers
+ 1
in other side it is good way how to understand how LinkedList works
25th Jun 2021, 7:29 PM
zemiak
+ 1
surely name 'head' for temporary currentPosition variable is really confusing, Maybe there is not enough understanding of LinkedList. I looked at some C++ implementations and there was same as in java: head and temporary variable for traversing
26th Jun 2021, 6:27 AM
zemiak
0
this del() method can't delete data in head, so it identifyies that last element in list is current.next.null and then current.next can be deleted 10 20 30 40 null list curr: 10 (30 is not null) true curr: 20 (40 is not null) true curr: 30 (40.next is null) end of loop 40 = null // delete last element 10 20 30 null list
25th Jun 2021, 7:37 AM
zemiak