資料結構(1):棧

ITWUYI發表於2020-10-19

資料結構之棧知識點

1、靜態棧(用陣列實現)

程式碼實現:

public class StackDemo {
    private int size;//大小或者容量
    private long arr[];//容器
    private int top;//棧頂
    public StackDemo(int maxsize){
        this.size = maxsize;
        this.arr = new long[maxsize];
        //初始化棧頂,表示為空
        this.top = -1;
    }
    //入棧
    public void push(int x){
        if (isFull()){
            System.out.println("棧已滿。");
            return;
        }
        //++top是先+1再運算,所以是從0開始的
        //而top++是先運算再加1,所以是從-1開始的
        //這裡是arr[0]表示第一個元素,後續繼續加1
        arr[++top] = x;
    }
    //檢視棧頂元素,不刪除
    public long peek(){
        if (isEmpty()){
            System.out.println("棧為空。");
            return -1;
            //throw new RuntimeException("棧是空的");
        }
        return arr[top];
    }
    //彈出棧頂元素,刪除,並返回棧頂元素
    public long pop(){
        if (isEmpty()){
            System.out.println("棧為空。");
            return -1;
        }
        return arr[top--];
    }
    //遍歷棧,從棧頂開始遍歷
    public void ergodic(){
        for (long i = top;top>-1;top--){
            System.out.println(arr[top]);
        }
    }
    //判斷棧是否已滿
    public boolean isFull(){
        return size == top - 1;
    }
    //判斷棧是否為空
    public boolean isEmpty(){
        return top == -1;
    }
}

2、動態棧(用連結串列實現)

程式碼實現:

public class LinkedStackDemo {
    private Node topStack;//棧頂指標
    private Node bottomStack;//棧底指標
    public int size;
    public LinkedStackDemo() {}
    public LinkedStackDemo(Node topStack,Node bottomStack){//初始化棧
        this.topStack = topStack;
        this.bottomStack = bottomStack;
        this.size = 0;
    }
    //入棧
    public void push(int data){
        Node node = new Node(data);
        //引用物件的next指向棧頂節點物件,則棧頂節點物件原先指向的節點,該引用物件新節點的next也同樣指向原先指向的節點
        node.next = this.topStack;
        this.topStack = node;
        size++;
    }
    //彈出棧頂元素,並刪除,返回棧頂數值
    public int pop(){
        if (isEmpty()){
            System.out.println("棧為空。");
            return -1;
        }
        int i = this.topStack.data;
        this.topStack = this.topStack.next;
        size--;
        return 1;
    }
    //檢視棧頂數值
    public int peek(){
        if (isEmpty()){
            System.out.println("棧為空。");
            return -1;
        }
        return  this.topStack.data;
    }
    //遍歷棧,從棧頂開始
    public void ergodic(){
        Node currentNode = topStack;
        while (currentNode!=null){
            System.out.println(currentNode.data);
            currentNode = currentNode.next;
        }
    }
    //檢視棧中值的數目
    public int size(){
        return size;
    }
    //清空棧
    public void clear(){
        this.topStack = this.bottomStack;//使棧頂元素指向棧底即可清空棧
    }
    //判斷棧是否為空
    public boolean isEmpty(){
        return size == 0;
    }
}
//節點類
class Node{
    public int data;
    public Node next;
    public Node(int data){
        this.data = data;
    }
}

後續如有更優的方法,會繼續補充。

相關文章