数据结构——链式栈
程序员文章站
2022-06-05 17:28:55
...
本篇文章主要是用做代码分享。代码,注释都写得很清楚,不清楚的可以问我,如果有些不对的地方也可以提出来,以便我及时改正。
接口类
public interface ILinkStack<E> {
boolean isEmpty(); //判空
boolean isFull(); //判满
boolean push(E element); //入栈
E pop(); //出栈
E peek(); //查看栈顶元素,不改变栈顶指针
}
结点类
//结点类
public class Node<E> {
private E data; //数据域
private Node<E> next; //指针域,或地址域
public Node(E data, Node<E> next) {
super();
this.data = data;
this.next = next;
}
public Node(E data) {
super();
this.data = data;
}
public Node() {
super();
}
public E getData() {
return data;
}
public void setData(E data) {
this.data = data;
}
public Node<E> getNext() {
return next;
}
public void setNext(Node<E> next) {
this.next = next;
}
}
链栈类
// 链式栈(使用泛型)
public class LinkStack<E> implements ILinkStack<E>{
private Node<E> top; //栈顶指针
public LinkStack(Node<E> top) { //构造链栈,初始为空
super();
this.top = null;
}
public LinkStack() {
super();
}
@Override
public boolean isEmpty() {
// 判空
return top == null;
}
@Override
public boolean isFull() {
// 判满
return false;
}
@Override
public boolean push(E element) {
// 入栈
if(element == null)
return false;
top = new Node<E>(element,top);
return true;
}
@Override
public E pop() {
// 出栈
if(!isEmpty()){
E temp = top.getData(); //取得栈顶元素值
top = top.getNext(); //出栈,指针后移
return temp;
}else
return null;
}
@Override
public E peek() {
// 查看栈顶元素,不改变栈顶指针
if(!isEmpty())
return top.getData();
else
return null;
}
}
测试类
import java.util.*;
//十进制转换为二进制
public class TestLinkStack01 {
public static void main(String[] args) {
LinkStack<Integer> stack = new LinkStack<Integer>();
Scanner input = new Scanner(System.in);
System.out.println("输入一个十进制的数:");
int num = input.nextInt();
while(num != 0){
stack.push(num % 2);
num /= 2;
}
System.out.print("二进制数是:");
while(!stack.isEmpty())
System.out.print(stack.pop());
}
}
上一篇: 获取程序编译后链接脚本中变量