i know can change element position creating new node , play node references. how can change element position without creating or deleting node, play node references? many thanks!
public class linkedlist<e extends comparable<e>> implements iterable<e> { private node head; // reference first node private int n; // number of elements stored in list private class node { public e item; public node next; public node() { item = null; next = null; } public node(e e, node ptr) { item = e; next = ptr; } } public boolean move(e e){ node current=head; while(current !=null){ if(e.equals(current.item)){ system.out.println("true"); return true; *****then how move node front? without creating , deleting nodes****** } current=current.next; } system.out.println("false"); return false;
your algorithm should this
int count = 1; // change 0 if zero-indexed node p = null; // previous node n = head; // current while(count < k) { if(n.next != null) { p = n; n = n.next; count++; } else break; } if(count == k){ p.next = n.next; n.next = head; head = n; }
Comments
Post a Comment