本文根据《大话数据结构》一书,实现了Java版的栈的顺序存储结构、两栈共享空间、栈的链式存储机构

:限定仅在表尾进行插入和删除操作的线性表。

栈的插入(进栈)和删除(出栈)操作如下图所示。

 【Java】 大话数据结构(6) 栈的顺序与链式存储  【Java】 大话数据结构(6) 栈的顺序与链式存储

 

1.栈的顺序存储结构

  用数组存放数据,top变量来指示栈顶元素在数组中的位置(栈顶指针)。一个长度为5的栈的示意图如下:

【Java】 大话数据结构(6) 栈的顺序与链式存储

  实现程序:

/**
 * 栈的顺序储存结构
 * 
 * 问题:构造器中,泛型数组创建是否有更好的方法?
 * @author Yongh
 *
 */
public class SqStack<E> {
	private E[] data;
	private int top;  //栈顶指针,top=-1时为空栈
	private int maxSize;
	private static final int DEFAULT_SIZE= 10;
	
	public SqStack() {
		this(DEFAULT_SIZE);
	}
	public SqStack(int maxSize) {
		//无法创建泛型数组 data=new E[maxSize];
		data=(E[]) new Object[maxSize];
		top=-1;
		this.maxSize=maxSize;
	}
	
	public void push(E e) {
		if(top==maxSize-1) 
			throw new RuntimeException("栈已满,无法进栈!");
		top++;
		data[top]=e;
	}
	
	public E pop() {
		if(top==-1)
			throw new RuntimeException("空栈,无法出栈!");
		E e=data[top];
		top--;
		return e;
	}
	
	public void printStack() {
		if(top==-1) {
			System.out.println("空栈");			
		}else {
			for(int i=0;i<=top;i++) {
				System.out.println(data[i]);
			}
		}		
	}
}

  

  测试代码:

public class StackTest {
	public static void main(String[] args) {
		SqStack<Student> sqStack=new SqStack<Student>();		
	    Student[] students= {new Student("小A",11),new Student("小B",12),new Student("小C",13),
	            new Student("小D",14),new Student("小E",151)};
	    for(int i=0;i<5;i++) {
	    	sqStack.push(students[i]);
	    }
	    sqStack.printStack();
	    for(int i=0;i<5;i++) {
	    	sqStack.pop();
	    }
	    sqStack.printStack();	    
	}       
}

class Student{
    public Student(String name, int age) {
        this.name=name;
        this.age=age;
    }
    String name;
    int age;
    public String toString() {
    	return name;
    }
}

  

小A
小B
小C
小D
小E
空栈
StackTest

相关文章:

  • 2022-02-04
  • 2021-12-03
  • 2021-08-22
  • 2022-12-23
  • 2021-09-19
  • 2022-12-23
  • 2022-01-11
  • 2022-02-23
猜你喜欢
  • 2022-12-23
  • 2021-11-07
  • 2022-12-23
  • 2021-08-01
  • 2022-12-23
  • 2022-12-23
  • 2021-06-29
相关资源
相似解决方案