-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathImplementQueueByLinkedList.java
More file actions
63 lines (54 loc) · 1.28 KB
/
ImplementQueueByLinkedList.java
File metadata and controls
63 lines (54 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/*Implement Queue by Linked List
Implement a Queue by linked list. Support the following basic methods:
1.enqueue(item). Put a new item in the queue.
2.dequeue(). Move the first item out of the queue, return it.
Example
enqueue(1)
enqueue(2)
enqueue(3)
dequeue() // return 1
enqueue(4)
dequeue() // return 2
Tags Expand
Linked List Queue
*/
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
this.next = null;
}
}
public class Queue {
private ListNode head = null;
private ListNode tail = null;
public Queue() {
tail = head;
}
public void enqueue(int item) {
ListNode i = new ListNode(item);
if (head == null) {
head = tail = i;
} else {
tail = tail.next = i;
}
}
public int dequeue() {
if (head == null) {
throw new java.util.NoSuchElementException();
}
if (head != null && head == tail) {
ListNode tmp = head;
head = head.next;
tail = head;
tmp.next = null;
return tmp.val;
} else {
ListNode tmp = head;
head = head.next;
tmp.next = null;
return tmp.val;
}
}
}