java - Circularly linked list remove tail without loop -
i tried implement circularly linked list , had read complexity of removing tail (which has direct reference) o(1). can't rid of tail reference without looping , resulting in complexity of o(n) , wondering if @ possible without looping?
remove = tail; prev = temp = tail.getnext(); { prev = temp; temp = temp.getnext(); } while(!temp.getnext().equals(tail.getnext())); prev.setnext(temp.getnext()); size--; return remove;
note: prev, temp, removeare local , tail tail of list , first instance of tail.getnext() head.
i had tried below not work node before tail still points tail , reference isn't removed. know need make tail's previous point head in order remove tail , above code this, i'm unsure how , if it's possible without looping through list..
remove = tail; tail= lastnode.getnext(); size--; return remove;
in circularly linked list every node has previous , next. there head pointer first node, , previous tail node, next head node.
so
node removetail() { if (head == null) { return null; } node tail = head.previous; node newtail = tail.previous; newtail.next = head; head.previous = newtail; if (head == tail) { head = null; } --size; return tail; // if desired. }
Comments
Post a Comment