stack
数组实现
details
class Stack {
constructor() {
this.stack = [];
}
push(val) {
this.stack.push(val);
}
peek() {
if (this.isEmpty()) {
return null;
}
return this.stack.at(-1);
}
pop() {
if (this.isEmpty()) {
return null;
}
return this.stack.pop();
}
isEmpty() {
return this.stack.length === 0;
}
size() {
return this.stack.length;
}
}
Rust
use super::ListNode;
pub struct Stack<T> {
stack: Vec<T>,
}
impl<T> Stack<T> {
pub fn new() -> Self {
Stack { stack: Vec::new() }
}
pub fn push(&mut self, val: T) {
self.stack.push(val);
}
pub fn pop(&mut self) -> Option<T> {
self.stack.pop()
}
pub fn peek(&self) -> Option<T>
where
T: Copy,
{
self.stack.last().copied()
}
pub fn is_empty(&self) -> bool {
self.stack.len() == 0
}
pub fn size(&self) -> usize {
self.stack.len()
}
}
链表实现
Javascript
class ListNode {
constructor(val, next = null) {
this.val = val;
this.next = next;
}
}
class Stack {
constructor() {
this.head = null;
this.size = 0;
}
push(val) {
this.head = new ListNode(val, this.head);
this.size++;
}
peek() {
if (this.isEmpty()) {
return null;
}
return this.head.val;
}
pop() {
if (this.isEmpty()) {
return null;
}
let node = this.head;
this.head = this.head.next;
this.size--;
return node.val;
}
isEmpty() {
return this.head === null;
}
size() {
return this.size;
}
}
Rust
use super::ListNode;
use std::{cell::RefCell, rc::Rc};
pub struct Stack<T> {
head: Option<Rc<RefCell<ListNode<T>>>>,
size: usize,
}
impl<T> Stack<T> {
pub fn new() -> Self {
Self {
head: None,
size: 0,
}
}
pub fn push(&mut self, val: T) {
let node = Rc::new(RefCell::new(ListNode {
val,
next: self.head.take(),
}));
self.head = Some(node);
self.size += 1;
}
pub fn pop(&mut self) -> Option<T> {
self.head.take().map(|node| {
let node = Rc::try_unwrap(node).ok().unwrap().into_inner();
self.head = node.next;
self.size -= 1;
node.val
})
}
pub fn peek(&self) -> Option<T>
where
T: Copy,
{
self.head.as_ref().map(|node| node.borrow().val)
}
pub fn is_empty(&self) -> bool {
self.head.is_none()
}
pub fn size(&self) -> usize {
self.size
}
}