-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathImplementQueueByLinkedListII.java
More file actions
95 lines (83 loc) · 2.17 KB
/
ImplementQueueByLinkedListII.java
File metadata and controls
95 lines (83 loc) · 2.17 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/*Implement Queue by Linked List II
Implement a Queue by linked list. Provide the following basic methods:
1.push_front(item). Add a new item to the front of queue.
2.push_back(item). Add a new item to the back of the queue.
3.pop_front(). Move the first item out of the queue, return it.
4.pop_back(). Move the last item out of the queue, return it.
Example
push_front(1)
push_back(2)
pop_back() // return 2
pop_back() // return 1
push_back(3)
push_back(4)
pop_front() // return 3
pop_front() // return 4
Tags Linked List Queue
*/
class ListNode {
int val;
ListNode next;
ListNode prev;
ListNode(int val) {
this.val = val;
next = null;
prev = null;
}
}
public class Dequeue {
private ListNode head = null;
private ListNode tail = null;
public Dequeue() {
// do initialize if necessary
head = tail = null;
}
public void push_front(int item) {
ListNode node = new ListNode(item);
// Write your code here
if (head == null) {
head = tail = node;
} else {
head.prev = node;
node.next = head;
head = node;
}
}
public void push_back(int item) {
// Write your code here
ListNode node = new ListNode(item);
if (tail == null) {
head = tail = node;
} else {
tail.next = node;
node.prev = tail;
tail = node;
}
}
public int pop_front() {
ListNode tmp = head;
if (head == null) {
throw new java.util.NoSuchElementException();
} else if (head == tail) {
tail = head = head.next;
return tmp.val;
} else {
head = head.next;
head.prev = tmp.prev;
return tmp.val;
}
}
public int pop_back() {
ListNode tmp = tail;
if (tail == null) {
throw new java.util.NoSuchElementException();
} else if (head == tail) {
head = tail = tail.next;
return tmp.val;
} else {
tail.prev.next = tail.next;
tail = tail.prev;
return tmp.val;
}
}
}