栈的理解
栈是线性数据结构的一种,数据在栈中呈现线性排列,同时数据具备先进后出的特点,我们只能针对栈的单端进行一系列数据操作。通过以上特点,我们会发现其与链表极其相似,我们利用头部添加法生成的链表,其中的数据类似于先进后出,所以我们可以利用链表来实现栈。
实现的栈方法
push()方法:向栈中添加元素
pop()方法:弹出栈顶部元素
peek()方法:返回栈顶部元素但不弹出
size()方法:返回栈的大小,即栈含有的元素数量
isEmpty()方法:查看栈是否为空
getMin()方法:得到栈中最小元素
代码解释
针对空栈情况,如果此时pop()或peek()或getMin(),则会返回-1;
代码展示
public class Stack {
ListNode head;
public Stack() {
head = null;
}
public void push(int x) {
head = new ListNode(x,head);
}
public void pop() {
if(head==null)
return;
head = head.next;
}
public int peek() {
if(head!=null)
return head.val;
return -1;
}
public int getMin() {
int min;
ListNode p =head;
if(p.next==null)
return p.val;
else if(p==null)
return -1;
else {
min = p.val;
}
while(p.next!=null){
if(min>p.next.val)
min = p.next.val;
p=p.next;
}
return min;
}
public boolean isEmpty(){
if(head==null)
return true;
return false;
}
public int size(){
int count = 0;
for(ListNode p =head;p!=null;p=p.next){
count++;
}
return count;
}
}
1959

被折叠的 条评论
为什么被折叠?



