Advertisement
Guest User

Untitled

a guest
Jan 25th, 2020
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.41 KB | None | 0 0
  1. package msqueue;
  2.  
  3. import kotlinx.atomicfu.AtomicRef;
  4.  
  5. public class MSQueue implements Queue {
  6. private AtomicRef<Node> head;
  7. private AtomicRef<Node> tail;
  8.  
  9. public MSQueue() {
  10. Node dummy = new Node(0);
  11. head = new AtomicRef<>(dummy);
  12. tail = new AtomicRef<>(dummy);
  13. }
  14.  
  15. @Override
  16. public void enqueue(int x) {
  17. Node newTail = new Node(x);
  18. while (true) {
  19. Node curTail = tail.getValue();
  20. if (tail.getValue().next.compareAndSet(null, newTail)) {
  21. tail.compareAndSet(curTail, newTail);
  22. break;
  23. } else {
  24. tail.compareAndSet(curTail, curTail.next.getValue());
  25. }
  26. }
  27. }
  28.  
  29. @Override
  30. public int dequeue() {
  31. while (true) {
  32. Node curHead = head.getValue();
  33. Node nextHead = curHead.next.getValue();
  34. Node curTail = tail.getValue();
  35. if (curHead == curTail) {
  36. if (nextHead == null) {
  37. return Integer.MIN_VALUE;
  38. } else {
  39. tail.compareAndSet(curTail, curTail.next.getValue());
  40. }
  41. } else {
  42. if (nextHead == null) {
  43. return Integer.MIN_VALUE;
  44. } else {
  45. if (head.compareAndSet(curHead, nextHead)) {
  46. return nextHead.x;
  47. }
  48. }
  49. }
  50. }
  51. }
  52.  
  53. @Override
  54. public int peek() {
  55. while (true) {
  56. Node curHead = head.getValue();
  57. Node nextHead = curHead.next.getValue();
  58. Node curTail = tail.getValue();
  59. if (curHead == curTail) {
  60. if (nextHead == null) {
  61. return Integer.MIN_VALUE;
  62. } else {
  63. tail.compareAndSet(curTail, curTail.next.getValue());
  64. }
  65. } else {
  66. if (nextHead == null) {
  67. return Integer.MIN_VALUE;
  68. } else {
  69. if (head.getValue() == curHead) {
  70. return nextHead.x;
  71. }
  72. }
  73. }
  74. }
  75. }
  76.  
  77. private class Node {
  78. final int x;
  79. AtomicRef<Node> next = new AtomicRef<>(null);
  80. Node(int x) {
  81. this.x = x;
  82. }
  83. }
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement