java LinkedList 堆栈队列

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;
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值