看到面试宝典上面的一道题: 实现一个栈操作,将1-12月的英文单词压入栈中,然后再将其取出,使用java代码实现。比照着它的答案,程序运行不正确,就自己慢慢的做出来了。主要使用了两种方法:顺序栈和链栈,直接上程序吧。
参考资料:http://blog.csdn.net/wuwenxiang91322/article/details/12231657
顺序栈实现:
package com.stack;
import java.util.*;
public class Stack{
private int maxSize;
private int top;
private String [] stackArrary;
static String [] months = {"January", "February", "March", "April","May", "June", "July",
"August","September","October","November","December"};
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Stack stk = new Stack(15);
for(int i = 0;i<months.length;i++)
stk.push(months[i]+" ");
while(!stk.isEmpty())
{
System.out.println(stk.pop());
System.out.println(" ");
}
}
public Stack(int s)
{
maxSize = s;
stackArrary = new String[maxSize];
top = -1;
}
public void push(String s) {
// TODO Auto-generated method stub
stackArrary[++top] = s;
}
public String pop()
{
return stackArrary[top--];
}
public boolean isEmpty() {
return (top == -1);
}
}
运行结果:
December
November
October
September
August
July
June
May
April
March
February
January
2.链栈来实现
package com.stack;
/*
* 链栈的实现
*/
public class LinkStack<T> {
static String [] months = {"January", "February", "March", "April","May", "June", "July",
"August","September","October","November","December"};
public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
LinkStack<String> stack = new LinkStack<String> ();
//入栈
for(int j=0;j<months.length;j++)
{
stack.push(months[j]+"");
}
//访问栈顶元素
System.out.println("访问栈顶元素:"+ stack.peek());
while(!stack.empty())
{
i++;
System.out.println("第"+i+"次弹出栈顶元素:"+stack.pop());
}
}
// 定义节点数据结构
private class Node{
public T data;
public Node next;
public Node(T data, Node next)
{
this.next = next;
this.data = data;
}
}
// 栈顶元素
private Node top;
// 元素的个数
private int size;
// 插入数据
public void push(T element)
{
top = new Node(element,top);
size++;
}
// 出栈
public T pop()
{
Node oldNode = top;
top = top.next;
// 释放引用
oldNode.next = null;
size--;
return oldNode.data;
}
// 返回栈顶的元素,但不出栈
public T peek()
{
return top.data;
}
// 链栈的长度
public int length()
{
return size;
}
// 判断链栈是否是空栈
public boolean empty()
{
return size ==0;
}
}
运行结果:
访问栈顶元素:December
第1次弹出栈顶元素:December
第2次弹出栈顶元素:November
第3次弹出栈顶元素:October
第4次弹出栈顶元素:September
第5次弹出栈顶元素:August
第6次弹出栈顶元素:July
第7次弹出栈顶元素:June
第8次弹出栈顶元素:May
第9次弹出栈顶元素:April
第10次弹出栈顶元素:March
第11次弹出栈顶元素:February
第12次弹出栈顶元素:January