Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Node{
- int data;
- Node prev;
- Node next;
- public Node(int data){
- this.data = data;
- }
- public void tampil(){
- System.out.println("{"+data+"}");
- }
- }
- public class CircularLL {
- Node first;
- Node last;
- int size;
- public CircularLL(){
- first = null;
- last = null;
- }
- public boolean isEmpty(){
- return(first==null);
- }
- public void insertFirst(int data){
- Node node = new Node(data);
- if(isEmpty()){
- last = node;
- first = node;
- }else{
- node.next = first;
- first.prev = node;
- }
- first = node;
- first.prev = last;
- last.next = first;
- size++;
- }
- public void insertLast(int data){
- Node node = new Node(data);
- if(isEmpty()){
- last = node;
- first = node;
- }else{
- node.prev = last;
- last.next = node;
- }
- last = node;
- first.prev = last;
- last.next = first;
- size++;
- }
- public void displayForward(){
- System.out.println("List (first-->last): "+size);
- Node current = first;
- int no =1;
- while(no <= size){
- current.tampil();
- current = current.next;
- no++;
- }
- System.out.println("");
- }
- public void displayBackward(){
- System.out.println("List (last-->first): "+size);
- Node current = last;
- int no =1;
- while(no <= size){
- current.tampil();
- current = current.prev;
- no++;
- }
- System.out.println("");
- }
- public Node deleteFirst(){
- Node temp = first;
- if(first.next == null){
- last = null;
- }else{
- first.next.prev = last;
- first = first.next;
- last.next = first;
- }
- size--;
- return temp;
- }
- public Node deleteLast(){
- Node temp = last;
- if(first.next == null){
- last = null;
- }else{
- last.prev.next = first;
- last = last.prev;
- first.prev = last;
- }
- size--;
- return temp;
- }
- public Node deleteKey(int key){
- Node current = first;
- while(current.data != key){
- current = current.next;
- }
- if(current==first){
- current = deleteFirst();
- }else if(current==last){
- current = deleteLast();
- }else{
- current.next.prev = current.prev;
- current.prev.next = current.next;
- }
- size--;
- return current;
- }
- public void display(){
- Node current = last.prev;
- current.tampil();
- System.out.println("");
- }
- public boolean insertAfter(int key, int data){
- Node current = first;
- while(current.data != key){
- current = current.next;
- }
- Node node = new Node(data);
- if(current==last){
- insertLast(data);
- }else{
- current.next.prev = node;
- node.next = current.next;
- node.prev = current;
- current.next = node;
- size++;
- }
- return true;
- }
- public static void main(String[] args){
- CircularLL list = new CircularLL();
- list.insertFirst(1);
- list.insertFirst(2);
- list.insertFirst(3);
- list.insertFirst(4);
- list.insertLast(0);
- list.insertLast(5);
- list.displayForward();
- list.deleteLast();
- list.displayForward();
- list.deleteKey(55);
- list.insertAfter(5,10);
- list.displayForward();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement