1、栈的实现
1)栈的功能:进栈、出栈、返回栈口元素……
2)详解的过程看代码吧:
import java.util.*;
//1借助LinkedList 类中的方法实现栈
public class MyStack {
private LinkedList<Object> li=new LinkedList<Object>();
//1构造方法
public MyStack(){
}
//2出栈
public Object pop(){
if(isEmpty()){
throw new EmptyStackException();
}
return li.removeFirst();
}
//3进栈
public void push(Object obj){ //注意o不要0的区别,不要写成0了
li.addFirst(obj);
}
//4清空
public void clear() {
li.clear();
}
//5判断是否为空
public boolean isEmpty(){
return li.isEmpty();
}
//6 将对象转换成字符串
public String toString(){
return li.toString();
}
//7返回栈口元素
public Object peek(){
if(isEmpty()){
throw new EmptyStackException();
}
return li.peekFirst();
}
public static void main(String[] args) {
MyStack stack=new MyStack();
//进栈
stack.push("a");
stack.push("b");
//出栈
System.out.println(stack.pop());
//返回栈口元素
System.out.println(stack.peek());
}
}
2、队列的实现:
1)队列的功能:队尾进,队首出、....
2)详细的见代码:
import java.util.*;
//借助LinkedList 类中的方法实现队列
public class MyQueue {
private LinkedList<Object> li = new LinkedList<Object>();
// 1构造方法
public MyQueue() {
}
// 2出列
public Object get() {
if (isEmpty()) {
throw new EmptyStackException();
}
return li.removeFirst();
}
// 3进列
public void put(Object obj) {
li.addLast(obj);
}
// 4清空
public void clear() {
li.clear();
}
// 5 返回队列首元素(不删除)
public Object getTop() {
if (isEmpty()) {
throw new EmptyStackException();
}
return li.peekFirst();
}
// 6将对象转换成字符串
public String toString() {
return li.toString();
}
// 7判断队列是否为空
public boolean isEmpty() {
return li.isEmpty();
}
public static void main(String[] args) {
MyQueue mq = new MyQueue();
// 进列
mq.put("a");
mq.put("b");
mq.put("c");
// 出列
System.out.println(mq.get());
System.out.println(mq.get());
// 返回对首元素
System.out.println(mq.getTop());
}
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"> </span>