Advertisement
Guest User

Untitled

a guest
Feb 14th, 2016
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.40 KB | None | 0 0
  1.  
  2. public class CircularLinkedList {
  3.  
  4. public int size =0;
  5. public Node head=null;
  6. public Node tail=null;
  7.  
  8. //add a new node at the start of the linked list
  9. public void addNodeAtStart(int data){
  10. System.out.println("Adding node " + data + " at start");
  11. Node n = new Node(data);
  12. if(size==0){
  13. head = n;
  14. tail = n;
  15. n.next = head;
  16. }else{
  17. Node temp = head;
  18. n.next = temp;
  19. head = n;
  20. tail.next = head;
  21. }
  22. size++;
  23. }
  24.  
  25. public void addNodeAtEnd(int data){
  26. if(size==0){
  27. addNodeAtStart(data);
  28. }else{
  29. Node n = new Node(data);
  30. tail.next =n;
  31. tail=n;
  32. tail.next = head;
  33. size++;
  34. }
  35. System.out.println("\nNode " + data + " is added at the end of the list");
  36. }
  37.  
  38. public void deleteNodeFromStart(){
  39. if(size==0){
  40. System.out.println("\nList is Empty");
  41. }else{
  42. System.out.println("\ndeleting node " + head.data + " from start");
  43. head = head.next;
  44. tail.next=head;
  45. size--;
  46. }
  47. }
  48.  
  49. public int elementAt(int index){
  50. if(index>size){
  51. return -1;
  52. }
  53. Node n = head;
  54. while(index-1!=0){
  55. n=n.next;
  56. index--;
  57. }
  58. return n.data;
  59. }
  60.  
  61. //print the linked list
  62. public void print(){
  63. System.out.print("Circular Linked List:");
  64. Node temp = head;
  65. if(size<=0){
  66. System.out.print("List is empty");
  67. }else{
  68. do {
  69. System.out.print(" " + temp.data);
  70. temp = temp.next;
  71. }
  72. while(temp!=head);
  73. }
  74. System.out.println();
  75. }
  76.  
  77. //get Size
  78. public int getSize(){
  79. return size;
  80. }
  81.  
  82. public static void main(String[] args) {
  83. CircularLinkedList c = new CircularLinkedList();
  84. c.addNodeAtStart(3);
  85. c.addNodeAtStart(2);
  86. c.addNodeAtStart(1);
  87. c.print();
  88. c.deleteNodeFromStart();
  89. c.print();
  90. c.addNodeAtEnd(4);
  91. c.print();
  92. System.out.println("Size of linked list: "+ c.getSize());
  93. System.out.println("Element at 2nd position: "+ c.elementAt(2));
  94. }
  95.  
  96. }
  97.  
  98. class Node{
  99. int data;
  100. Node next;
  101. public Node(int data){
  102. this.data = data;
  103. }
  104. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement