Advertisement
Guest User

noobs2

a guest
Jan 27th, 2015
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. package liu_apCompSci;
  2.  
  3. import java.util.Arrays;
  4.  
  5. public class RingBuffer {
  6. // instance variables
  7. private char[] characters;
  8. private int front;
  9. private int rear;
  10.  
  11. // constructor
  12. public RingBuffer(int capacity) {
  13. characters = new char[capacity + 1];
  14. front = 0;
  15. rear = 0;
  16. }
  17.  
  18. // makes the front equal to rear without destroying any values in the middle
  19. public void flush() {
  20. front = rear;
  21. }
  22.  
  23. public boolean add(char ch) {
  24. // check if it's full
  25. if (rear - front == (characters.length - 1) || front - rear == 1) {
  26. return false;
  27. } else {
  28. // insert the value into the rear location
  29. characters[rear] = ch;
  30. // increment rear
  31. if (rear != characters.length - 1) {
  32. rear++;
  33. } else {
  34. // if it goes over the length of the array
  35. rear = 0;
  36. }
  37. return true;
  38. }
  39. }
  40.  
  41. // check if front equals rear, thereby making it empty
  42. public boolean isEmpty() {
  43. return front == rear;
  44. }
  45.  
  46. public char remove() {
  47. // check if it's full
  48. if (rear - front == (characters.length - 1) || front - rear == 1) {
  49. return ' ';
  50. } else {
  51. // increment the front
  52. if (front != characters.length - 1) {
  53. front++;
  54. // return the value that was last there
  55. return characters[front - 1];
  56. } else {
  57. // if it leaks over the length of the array
  58. front = 0;
  59. return characters[characters.length - 1];
  60. }
  61. }
  62. }
  63.  
  64. public char peek() {
  65. // check if it's empty
  66. if (front == rear) {
  67. return '!';
  68. } else {
  69. // look at the top value of the "queue"
  70. return characters[front];
  71. }
  72. }
  73.  
  74. // accessor method
  75. public int getFront() {
  76. return front;
  77. }
  78.  
  79. // accessor method
  80. public int getRear() {
  81. return rear;
  82. }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement