/**
- 链栈:
- 采用链式存储结构实现
- 技巧:
- 栈顶指针指向链表的第一个节点
- 时间复杂度:
- 插入:O(1)
- 删除:O(1)
- @author hopefully
*/
public class LinkStack<T> {
private Node<T> top;
private int length;
public LinkStack() {
top=null;
}
//is empty?
public boolean isEmpty() {
return top==null;
}
//push
public void push(T obj) {
/*Node<T> p=new Node<>(obj,null);
p.next=top;
top=p;
*/
top=new Node<T>(obj,top);
length++;
}
//出栈
public T pop() {
if(isEmpty()) {
System.out.println("栈空");
return null;
}
T res=top.data;
top=top.next;
length--;
return res;
}
//peek
public T peek() {
if(isEmpty()) {
System.out.println("栈空");
return null;
}
return top.data;
}
//遍历
public void traverse() {
Node<T> p=top;
while(p!=null) {
System.out.print(p.data+" ");
p=p.next;
}
System.out.println();
}
//栈长
public int size() {
return length;
}
//销毁
public void destroy() {
top=null;
}
public static void main(String[] args) {
LinkStack<Integer> linkStack=new LinkStack<Integer>();
for(int i=1;i<=20;i++) {
linkStack.push(i);
}
linkStack.traverse();
System.out.println(linkStack.pop());
System.out.println(linkStack.peek());
System.out.println(linkStack.size());
}
}
class Node<T>{
T data;
Node<T> next;
public Node(Node<T> n) {
next=n;
}
public Node(T obj, Node<T> n) {
data=obj;
next=n;
}
public T getData() {
return data;
}
public Node<T> getNext(){
return next;
}
}