package com.hao947.p004.Collection.LinkedList;
import java.util.*;
public class LinkStack {
public static void main(String args[]) {
Stack<Integer> it = new Stack<Integer>();// 申明Integer类型的栈
Queue<String> qt = new Queue<String>();// 申明String类型的队列
String list[] = { "Happy", "new", "Year", "to", "you", "The", "good",
"Day" };
System.out
.println("---------------------------模拟栈的相关操作--------------------------");
for (int i = 0; i < 10; i++) {
int p = (int) (Math.random() * 100);
it.push(p);
System.out.println(p + "-->入栈");
}// 依次让10个随机数入栈
System.out.println("栈顶元素为:" + it.top());
System.out.print("出栈顺序:");
while (!it.Isempty()) {// 依次出栈操作
System.out.print("-->" + it.top());
it.pop();
}
System.out.println("\n当前栈为空:" + it.Isempty());
System.out
.println("---------------------------模拟队列相关操作--------------------------");
for (int j = 0; j < list.length; j++) {// 入队操作
System.out.println("--> " + list[j] + " 进入队列");
qt.EnQueue(list[j]);
}
System.out.println("qt队列的对头元素为: " + qt.GetHead());
System.out.print("对列出对顺序:");
while (!qt.IsEmpty()) {// 元素依次出对
System.out.print("-->" + qt.GetHead());
qt.DeQueue();
}
System.out.println("\nqt队列为空队列:" + qt.IsEmpty());
System.out
.println("--------------------------------------------------------------");
}
}
// 采用LinkedList模拟堆栈
class Stack<E> {
private LinkedList<E> li;
Stack() {// 构造函数
li = new LinkedList<E>();
}
public void push(E obj) {// 入栈
li.addLast(obj);
}
public E top() {// 返回栈顶元素
if (!Isempty())
return li.getLast();
return null;
}
public void pop() {// 出栈
if (!Isempty())
li.removeLast();
else
System.out.println("栈为空不能执行弹栈操作");
}
public boolean Isempty() {// 判断是否为空栈
return li.isEmpty();
}
}
// 采用LinkedList模拟队列
class Queue<E> {
private LinkedList<E> li;// 队列数据区
Queue() {
li = new LinkedList<E>();
}
public boolean IsEmpty() {// 判断队列是否为空队列
return li.isEmpty();
}
public void EnQueue(E obj) {// 入队操作
li.addFirst(obj);
}
public void DeQueue() {// 出对操作
if (!IsEmpty())
li.removeLast();
else
System.out.println("队列已经为空!");
}
public E GetHead() {// 返回对头元素
if (!IsEmpty())
return li.getLast();
else
return null;
}
}
java LinkedList 堆栈队列
最新推荐文章于 2024-01-09 21:37:21 发布