Implementing Circular Linked List in java -


i'm having bit of issue implementing circularly linked list. i'm working on problem requires implement adt yourself. seem okay adding nodes list, i'm in unfamiliar territory when comes removing. included first 2 remove methods give idea of head at, how go removing last node in list?

public class linkedlist {     private node head;     private node tail;     private int size = 0;     linkedlist() {         head = null;         current = null;         previous = null;         tail = null;         size = 0;     }      //checks if list empty     public boolean isempty() {         return head == null;     }     //add new node front of circularly linked list     public void addtofront(e x) {         if (head == null) {             head = new node(x);         } else {             node n = new node(x);             x.next() = head;             head = x;         }     }      public void addtomiddle(e x) {         x.next = current.next();         current.next = x;         size = size + 1;     }      public void addtoend(e x) {         x.next = null;         tail.next() = x;         tail = x;         size = size + 1;     }      public void removefirst(e x) {         if (head = null) {             system.out.println("error! list empty!");         } else {             head = current.next();             size = size + 1;         }     }      public void removemiddle(e x) {         previous.next() = current.next();         current.next() = null;         size = size + 1;     } 

in circular linked list last node's next points head, loop through nodes until node.next.equals( head ). note next must never null , if have 1 node have head.next = head.

in circular doubly linked list have previous node, i.e. can iterate backwards. in case last node head.previous.

a small ascii picture:

head -next---> node -next---> node -next---> last  | ^  <---prev-      <---prev-      <---prev- | ^  | |                                          | |  | |_____________________________________next_| |  |_prev_________________________________________|       

Comments

Popular posts from this blog

1111. appearing after print sequence - php -

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

Ruby on Rails, ActiveRecord, Postgres, UTF-8 and ASCII-8BIT encodings -