Java 数据结构——链式栈
程序员文章站
2022-06-05 15:05:07
...
1 . 链式栈的定义。
链式栈的定义和单链表的定义一样。入栈采用单链表的头插法,出栈依然从第一个节点开始删除,刚好实现了栈先进后出的特点,链式栈不用判断栈空和栈满。
class LinkStack{
class Entry{
int data;
Entry next;
public Entry(){
this.data = -1;
this.next = null;
}
public Entry(int val){
this.data = val;
this.next = null;
}
}
Entry head = null;
public LinkStack(){
this.head = new Entry();
}
}
2.链式栈的基本操作。
a . 入栈。
用单链表的头插法插入一个元素即可。
public void push(int val){
Entry entry = new Entry(val);
entry.next = this.head.next;
this.head.next = entry;
}
b . 出栈。
删除头结点的下一个结点。
Entry cur = head.next;
if(cur == null){
return;
}
head.next = cur.next;
return;
}
c . 得到栈顶元素
栈顶元素即为头结点的下一个元素。
public int getTop(){
Entry cur = head.next;
if(cur == null){
return -1;
}
return cur.data;
}
d . 打印栈内元素。
public void show(){
Entry cur = this.head.next;
while(cur != null){
System.out.print(cur.data +" ");
cur = cur.next;
}
System.out.println();
}
上一篇: Java——数组栈的实现
下一篇: 增肌减脂食谱推荐