public class Node {
String name;
Node next;
public Node() {
name=null;
next=null;
}
public Node(String name) {
this(name,null);
}
public Node(String name,Node next ) {
this.name=name;
this.next=next;
}
}
public class MyStackDome1 {
Node head;
public MyStackDome1() {
head=new Node();
}
//新增
public void push(String data) {
Node h=head;
Node p=new Node(data);
p.next=h.next;
h.next=p;
}
//删除元素
public String pop() {
//判断堆栈是否为空
if(isEmpty()) {
System.out.println("堆栈已经为空无法删除");
return null;
}
Node p=head;
Node temp=p.next;
p.next=p.next.next;
return temp.name;
}
//判断堆栈是否为空
public boolean isEmpty() {
if(head.next==null) {
return true;
}
else
return false;
}
//返回元素个数
public int size() {
int num=0;
Node p=head;
while(p.next!=null) {
num++;
p=p.next;
}
return num;
}
//查找
public void find(String data) {
Node p=head;
while(p.next!=null) {
if(p.next.name.equals(data)) {
System.out.println("此信息存在");
break;
}
else {
p=p.next;
}
}
}
//获取栈顶元素
public String peek() {
if(isEmpty()) {
System.out.println("堆栈已经为空无法删除");
return null;
}
return head.next.name;
}
public static void main(String[] args) {
MyStackDome1 stack=new MyStackDome1();
stack.push("组长");
stack.push("部门经理");
stack.push("副总经理");
stack.push("总经理了");
stack.push("董事长");
System.out.println(stack.peek());
System.out.println(stack.size());
stack.pop();
System.out.println(stack.size());
}
}
堆栈的基本操作&&链式存储
最新推荐文章于 2023-09-08 11:26:42 发布