题目描述
使用链表实现一个栈简单的基本功能。
实现思路
1、首先自己定义一个链表节点类Node,再定义一个栈类Stack。
2、push方法:我们首先判断头节点是否为空,如果为空,就先new一个head节点,接着把值放入head节点,否则,先new一个node节点,把head节点接入node的下个节点,再把head节点指向node节点。
3、pop方法:如果head不为空说明栈中有值,把head节点的value拿出来,在把head节点往下走一步,原来的头节点回因为没有引用而被回收。
4、peek方法:返回head节点的值就行了。
其他的方法就很简单不用细说了。
代码实现
package stack;
public class Stack {
private Node head;
private int size = 0;
public void push(int value) {
if (head == null) {
head = new Node();
head.value = value;
}else {
Node node = new Node(value);
node.next = head;
head = node;
}
size++;
}
public int pop() {
if (head != null) {
int value = head.value;
head = head.next;
size--;
return value;
}else {
return -1;
}
}
public int peek() {
if (head != null) {
return head.value;
}
return -1;
}
public boolean isEmpty() {
return head != null;
}
public int size() {
return size;
}
public static void main(String[] args) {
Stack stack = new Stack();
stack.push(1);
stack.push(2);
stack.push(3);
int value = stack.peek();
System.out.println(value);
stack.pop();
System.out.println(stack.peek());
}
}
class Node {
int value;
Node next;
public Node(int value) {
this.value = value;
}
public Node() {}
}