1. 程式人生 > >java版資料結構與演算法—連結串列實現棧

java版資料結構與演算法—連結串列實現棧

package com.zoujc;

/**
 * 用連結串列實現棧
 */
class MyLinkStack {
    private Link first;
    public MyLinkStack(){
        first = null;
    }
    //判空
    public boolean isEmpty(){
        return first == null;
    }
    //從頭插入
    public void insertFirst(int dd){
        Link link = new Link(dd);
        link.
next = first; first = link; } //刪除 public int deleteFirst(){ Link tmp = first; first = first.next; return tmp.dData; } //顯示 public void display(){ Link current = first; while (current != null){ current.display(); current =
current.next; } System.out.println(""); } } class Link{ public int dData; public Link next; public Link(int dd){ dData = dd; } public void display(){ System.out.print(dData + " "); } } class LinkStack{ public MyLinkStack myLinkStack; public
LinkStack(){ myLinkStack = new MyLinkStack(); } //進棧 public void push(int data){ myLinkStack.insertFirst(data); } //出棧 public int pop(){ return myLinkStack.deleteFirst(); } //判空 public boolean isEmpty(){ return myLinkStack.isEmpty(); } //顯示 public void display(){ System.out.print("Stack:"); myLinkStack.display(); } public static void main(String[] args){ LinkStack linkStack = new LinkStack(); linkStack.push(20); linkStack.push(30); linkStack.push(40); linkStack.display(); linkStack.pop(); linkStack.pop(); linkStack.display(); } }

在這裡插入圖片描述