Skip to content

Commit d0a9453

Browse files
committed
1.3.29
1 parent 5afaba3 commit d0a9453

File tree

1 file changed

+72
-1
lines changed

1 file changed

+72
-1
lines changed

Ch_1_3/Ex_1_3_29.md

Lines changed: 72 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,82 @@ categories:
1414

1515
## Problem:
1616

17-
Write a Queue implementation that uses a circular linked list, which is the same as a linked list except that no links are null and the value of last.next is first when- ever the list is not empty. Keep only one Node instance variable (last).
17+
Write a Queue implementation that uses a circular linked list, which is the same as a linked list except that no links are null and the value of last.next is first whenever the list is not empty. Keep only one Node instance variable (last).
1818

1919
## Solution:
2020

2121

22+
**use only one instance variable**
23+
24+
```java
25+
public static class _Queue<Item> {
26+
27+
Node tail;
28+
29+
private class Node {
30+
31+
public Node(Item item) {
32+
this.item = item;
33+
}
34+
35+
Item item;
36+
Node next;
37+
}
38+
39+
/**
40+
* insert at last
41+
*/
42+
public void enqueue(Item item) {
43+
if (tail == null) {
44+
tail = new Node(item);
45+
tail.next = tail;
46+
} else {
47+
Node front = tail.next;
48+
Node n = new Node(item);
49+
tail.next = n;
50+
tail = n;
51+
tail.next = front;
52+
}
53+
}
54+
55+
public void print() {
56+
Node cur = tail.next;
57+
while (cur != tail) {
58+
StdOut.printf("%s->", cur.item);
59+
cur = cur.next;
60+
}
61+
StdOut.println(cur.item);
62+
}
63+
64+
public boolean isEmpty() {
65+
return tail == null;
66+
}
67+
68+
69+
/**
70+
* remove first element in queue
71+
*/
72+
public Item dequeue() {
73+
if (tail == tail.next) {
74+
Item item = tail.item;
75+
tail = null;
76+
return item;
77+
}
78+
Node front = tail.next;
79+
Item item = front.item;
80+
tail.next = front.next;
81+
return item;
82+
}
83+
}
84+
```
85+
86+
87+
88+
2289
## Reference:
2390

91+
[circular-queue-array](https://www.geeksforgeeks.org/circular-queue-set-1-introduction-array-implementation/)
92+
93+
[circular-queue-list](https://www.geeksforgeeks.org/circular-queue-set-2-circular-linked-list-implementation/)
2494

95+
[xiaoheigit](https://github.com/YangXiaoHei/Algorithms/blob/master/Ch_1_3_Bags_Queues_And_Stacks/Practise_1_3_29.java)

0 commit comments

Comments
 (0)