Advertisement
asp211

CircularLinkedList

Sep 18th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. public class CircularLinkedList {
  2. private ListNode last;
  3.  
  4. public CircularLinkedList() {
  5. last = null;
  6. }
  7.  
  8. public boolean isEmpty() {
  9. return last == null;
  10. }
  11.  
  12. public String toString() {
  13. String val = "";
  14. if (isEmpty()) {
  15. return "Error: Empty List";
  16. }
  17. ListNode curr = last.getNext();
  18. while (curr != last) {
  19. val += curr.getValue();
  20. curr = curr.getNext();
  21. }
  22. val += last.getValue();
  23. return val;
  24. }
  25.  
  26. public int size() {
  27. int val = 0;
  28. if (isEmpty()) {
  29. return 0;
  30. }
  31. ListNode curr = last.getNext();
  32. while (curr != last) {
  33. val++;
  34. curr = curr.getNext();
  35. }
  36. return val+1;
  37. }
  38.  
  39. public void addFirst(Object arg) {
  40. if (isEmpty()) {
  41. ListNode test = new ListNode(arg, last);
  42. test.setNext(test);
  43. }
  44. ListNode next = last.getNext();
  45. last.setNext(new ListNode(arg, next));
  46. }
  47. public Object removeFirst(Object arg) {
  48. if (isEmpty()) {
  49. return null;
  50. }
  51. ListNode first = last.getNext();
  52. if (last == first) {
  53. return first.getValue();
  54. }
  55. last.setNext(first.getNext());
  56. return first.getValue();
  57. }
  58. public void addLast(Object arg) {
  59. if (isEmpty()) {
  60. ListNode test = new ListNode(arg, last);
  61. test.setNext(test);
  62. }
  63. ListNode first = last.getNext();
  64. ListNode curr = first;
  65. while (curr != last) {
  66. curr = curr.getNext();
  67. }
  68. curr.setNext(new ListNode(arg, first));
  69. }
  70. public Object removeLast(Object arg) {
  71. if (isEmpty()) {
  72. return null;
  73. }
  74. ListNode first = last.getNext();
  75. if (last == first) {
  76. return first.getValue();
  77. }
  78. ListNode curr = first;
  79. while (curr.getNext() != last) {
  80. curr = curr.getNext();
  81. }
  82. curr.setNext(new ListNode(arg, first));
  83. return last;
  84. }
  85.  
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement