天天看點

利用連結清單和數組實作棧分别利用單向連結清單和數組實作棧

分别利用單向連結清單和數組實作棧

主菜單包含基本添加列印等功能

import java.util.Scanner;

public class ArrayStackDemo {
	public static void main(String[] args) {
		ArrayStack stack = new ArrayStack(4);
		String key = "";
		boolean loop = true;
		Scanner scanner = new Scanner(System.in);
		while(loop) {
			System.out.println("show:列印棧");
			System.out.println("exit:退出程式");
			System.out.println("push:入棧");
			System.out.println("pop:出棧");
			System.out.println("請輸入");
			key = scanner.next();
			switch(key) {
			case "show":
				stack.list();
				break;
			case "push":
				System.out.println("請輸入一個數:");
				int value = scanner.nextInt();
				stack.push(value);
				break;
			case "pop":
				try {
					int res = stack.pop();
					System.out.println("出棧的資料是:" + res);
				} catch (Exception e) {
					System.out.println(e.getMessage());
				}
				break;
			case "exit":
				scanner.close();
				loop = false;
				break;
			default:
					break;
			}
		}
		System.out.println("程式退出");
	}
}
           

利用數組實作棧

class ArrayStack {
	private int maxSize;
	private int[] stack;
	private int top = -1;

	public ArrayStack(int maxSize) {
		this.maxSize = maxSize;
		this.stack = new int[this.maxSize];
	}

	// 棧滿
	public boolean isFull() {
		return top == maxSize - 1;
	}

	// 棧空
	public boolean isEmpty() {
		return top == -1;
	}
	//入棧
	public void push(int value) {
		if(isFull()) {
			System.out.println("棧滿");
			return;
		}
		top++;
		stack[top] = value;
	}
	//出棧
	public int pop() {
		if(isEmpty()) {
			throw new RuntimeException("棧空,沒有資料");
		}
		int value = stack[top];
		top--;
		return value;
	}
	
	public void list() {
		if(isEmpty()) {
			System.out.println("棧空");
			return;
		}
		for(int i = top;i>=0;i--) {
			System.out.println("stack["+ i+ "] = " + stack[i]);			
		}
	}
	
}
           

利用連結清單實作棧

class LinkedStack {
	private int maxSize;
	private Node stack;
	private int top = 0;

	public LinkedStack(int maxSize) {
		this.maxSize = maxSize;
	}

	// 棧滿
	public boolean isFull() {
		return top == maxSize;
	}

	// 棧空
	public boolean isEmpty() {
		return top == 0;
	}

	// 入棧
	public void push(int value) {
		if (isFull()) {
			System.out.println("棧滿");
			return;
		}
		top++;
		Node node = new Node(value);
		if(stack != null) {
			node.next = stack;			
		}
		stack = node;
	}

	// 出棧
	public int pop() {
		if (isEmpty()) {
			throw new RuntimeException("棧空,沒有資料");
		}
		int value = stack.no;
		stack = stack.next;
		top--;
		return value;
	}
	
	public void list() {
		if (isEmpty()) {
			System.out.println("棧空");
			return;
		}
		Node temp = stack;
		while (temp != null) {
			System.out.println(temp);
			temp = temp.next;
		}
	}
}

class Node {
	public int no;
	public Node next;

	public Node(int no) {
		this.no = no;
	}

	@Override
	public String toString() {
		return "Node [no=" + no + "]";
	}
}
           

繼續閱讀