面试Java手写实现堆栈
程序员文章站
2022-04-12 22:45:46
面试时,面试面试官要求手写双链表,然后使用实现的双链表实现栈,不能使用jdk已提供的集合。贴代码,欢迎大家点评1.链表元素类实现/** * 链表元素类 */class Node{ private Node pre; private Node next; private Object value; public Node() { } public Node(Object value) { this.value = valu...
面试时,面试官要求手写双链表,然后使用实现的双链表实现栈,不能使用jdk已提供的集合。
贴代码,欢迎大家点评
1.链表元素类实现
/**
* 链表元素类
*/
class Node{
private Node pre;
private Node next;
private Object value;
public Node() {
}
public Node(Object value) {
this.value = value;
}
public Node(Node pre, Node next, Object value) {
this.pre = pre;
this.next = next;
this.value = value;
}
public Node getPre() {
return pre;
}
public void setPre(Node pre) {
this.pre = pre;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
@Override
public String toString() {
return "Node{" +
"value=" + value +
'}';
}
}
2.栈实现
/**
* 栈
*/
class Stack{
private Node top;
private Integer length = 0;
public synchronized void push(Node e){
if(!Objects.isNull(top)){
//新增节点前驱指针指向,当前节点
e.setPre(top);
//当前节点的后继指针指向,新增节点
top.setNext(e);
//设置当前节点为栈顶
top = top.getNext();
}else{
//边界处理
top = e;
}
length++;
}
public synchronized Node pop(){
Node tmp = new Node();
while (top.getNext() == null){
tmp.setValue(top.getValue());
top = top.getPre();
if(top == null){
length--;
return tmp;
}
//前驱指针置空
top.getNext().setPre(null);
//后驱指针置空
top.setNext(null);
//栈深减一
length--;
return tmp;
}
return tmp;
}
public Integer getLength() {
return length;
}
}
3.测试类
public static void main(String[] args) {
Stack stack = new Stack();
for(int i=0 ; i < 3 ; i++){
stack.push(new Node(new Integer(i)));
}
int len = stack.getLength();
for(int i=0 ; i<len ; i++){
System.out.println(stack.pop());
}
}
输入顺序0,1,2
输出结果
本文地址:https://blog.csdn.net/u011476733/article/details/109622346
上一篇: [Java数据结构]之哈希表如何避免冲突