题目地址:
https://www.lintcode.com/problem/implement-queue-by-linked-list/description
用链表实现队列。需要用head和tail标记链表的头和尾结点。在入队的时候需要判断一下队列是否为空,如果不空则直接在tail后面append一个新node即可,否则说明tail是null,直接new一个新node出来。代码如下:
public class MyQueue {
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
private ListNode head, tail;
/*
* @param item: An integer
* @return: nothing
*/
public void enqueue(int item) {
// write your code here
// 队列为空,则new一个新节点出来赋值给head和tail,
// 否则在tail后面new出一个新node并将tail后移
if (head == null) {
head = tail = new ListNode(item);
} else {
tail.next = new ListNode(item);
tail = tail.next;
}
}
/*
* @return: An integer
*/
public int dequeue() {
// write your code here
int res = head.val;
head = head.next;
return res;
}
}
所有方法时空复杂度 O ( 1 ) O(1) O(1)。