- 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; } } }
6 Respuestas
+ 1
in other side it is good way how to understand how LinkedList works
+ 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
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