当前位置:网站首页>One way linked list implements queue and stack
One way linked list implements queue and stack
2022-07-16 07:17:00 【Chenchen-】
One way list and two-way list
Single chain list : value , One next The pointer
Double linked list : value , One last The pointer , One next The pointer
Single linked list implementation queue
queue : fifo
You need two variables head and tail

public static class Node<V> {
public V value;
public Node<V> next;
public Node(V v) {
value = v;
next = null;
}
}
public static class MyQueue<V> {
private Node<V> head;
private Node<V> tail;
private int size;
// initialization
public MyQueue() {
head = null;
tail = null;
size = 0;
}
public boolean isEmpty() {
return size == 0;
}
public void offer(V value) {
Node<V> cur = new Node<V>(value);
if (tail == null) {
head = cur;
tail = cur;
} else {
tail.next = cur;
tail = cur;
}
size++;
}
// eject
public V poll() {
V ans = null;
if (head != null) {
ans = head.value;
head = head.next;
size--;
}
if (head == null) {
tail = null;
}
return ans;
}
// Take value only Don't pop up
public V peek() {
V ans = null;
if (head != null) {
ans = head.value;
}
return ans;
}
}Implementation stack
Stack : First in, then out
Just one variable , Stack a node ,head Point to a new node ,head = head.next
/**
* Single linked list implementation stack
*
* @param <V>
*/
public static class MyStack<V> {
private Node<V> head;
private int size;
public MyStack() {
head = null;
size = 0;
}
public boolean isEmpty() {
return size == 0;
}
public int size() {
return size;
}
public void push(V value) {
Node<V> cur = new Node<>(value);
if (head == null) {
head = cur;
} else {
cur.next = head;
head = cur;
}
size++;
}
public V pop() {
V ans = null;
if (head != null) {
ans = head.value;
head = head.next;
size--;
}
return ans;
}
public V peek() {
return head != null ? head.value : null;
}
}
边栏推荐
猜你喜欢

LeetCode精讲——873. 最长的斐波那契子序列的长度(难度:中等)

Leetcode lecture - 735 Planetary collision (difficulty: medium)

SAP Logon 无法正常启动

Small stage summary

C#基础到入门(一篇就够了)

Hardware course design: sensor device of multi-function player based on stm32

01. Write three listeners in a class

Hardware course design: small game of multi-function player based on stm32

Hardware course design: MP3 music playback of multi-function player based on stm32

redis基础知识——菜鸟教程
随机推荐
Gobang (2)
Chrome实现自动化测试:录制回放网页动作
Leetcode lecture - 676 Implement a magic Dictionary (difficulty: medium)
128. 最长连续序列
闭包那点事儿
What is EventLoop?
SAP ABAP BAPI_ACC_DOCUMENT_POST 创建会计凭证
Implementation of list class template of bidirectional linked list
MySQL 操作
【6月3号学习进度】
程序员日常技巧
ES6-ES11新特性(这一篇就够了)
Unity3d common components
Node.js 的 MySQL 操作
散列表HashTable分离链接法类模板的实现
Unity3d monobehavior base class
[learning records on June 5]
联想词匹配-总结
Unity2d mobile details official case exercise
redis基础知识——菜鸟教程