java - How should I implement removal of rightmost half of my custom Linkedlist -
write method removerightmosthalf
member of class linkedlist
. not call methods of class , not use auxiliary data structures.
if l
contains a! b! c! d! e
, after calling l.removerightmosthalf()
, l
becomes a! b! c
.
int size = 0 ; int halfsize = 0; current = head; while (current.next != null) { ++size; current=current.next; } ++size; if (size % 2 == 0) { halfsize = (size / 2); (int = halfsize + 1; < size; i++) { } }
i not know how remove inside loop. help!
i suggest use 2 pointers, slow
, fast
pointer. both pointing start of linked list.
- the slow pointer move 1 node @ time.
- the fast move 2 node time.
the moment see fast
pointer has reached end of list, mark slow pointer node end of list, setting next=null
;
important note that, discovery of end of list depend on even/odd size of list. design , test both cases.
Comments
Post a Comment