linked list - How to implement CircularLinkedList in Java without first & Last? -
a question in linkedlists book asks implement linkedlist without first , last pointers while allowing access list "current" pointer. not quite sure on right track, appreciated. here tried, insert/delete working...
class link { public int idata; public link next; public link(int id) // constructor { idata = id; } public void displaylink() { system.out.print(idata + " "); } } // end class link public class circularlinkedlist { private link current; private link first; //------------------------------------------------------------- public circularlinkedlist(){ current = null; } public circularlinkedlist(link link){ current = link; } public link getcurrent(){ return current; } public link getnext(){ return current.next; } public void setcurrent(link current){ this.current = current; } public void insert(int data){ link newlink = new link(data); //only link if(current == null){ current = newlink; first = current; }else{ current.next = newlink; } newlink.next = first; } public void delete(){ } public int find(int key){ return -1; } public void displaylist() { link tmp = current; while(current != null) // until end of list, { current.displaylink(); // print data current = current.next; // move next link if(current == tmp) break; } system.out.println(""); } public static void main(string ...args){ circularlinkedlist list = new circularlinkedlist(); list.insert(10); list.insert(20); list.insert(30); list.insert(40); list.displaylist(); } }
your link class needs set next value in constructor
public link (int id, link next)
then want list circular first link, next itself. when insert element a, make current.next a, , a.next previous value of current.next. delete id search until find (current.next in loop) , save previous element b each time. when find element searching set b.next b.next.next.