数据结构之链式栈

代码实现

/**
 * 链式栈
 * 
 * 
 * */

class linkstack{//定义一个链式栈的类
    Entry head=null;
    public linkstack(){
        this.head=new Entry();
    }
    class Entry{
        int data;
        Entry  next;
        public Entry(){//不含参数的构造函数
            this.data=-1;
            this.next=null;
        }
        public Entry(int data){//含参数的构造函数
            this.data=data;
            this.next=null;
        }

    }



    //入栈
    //链式栈入栈的时候我们使用头插法
    public void inserthead(int val){
        Entry entry =new Entry(val);
        entry.next=this.head.next;
        this.head.next=entry;

    }

    //出栈
    //因为栈是先进后出的,而且我们使用了头插法,所以我们只需删除第一个结点就行
    public void  pop(){
        Entry cur=this.head.next;

       head.next=cur.next;

        }

    //得到栈顶元素
    public int gettop(){//直接返回第一个结点的data就是栈顶元素
        return this.head.next.data;
    }
    public void show(){
        Entry cur=this.head.next;
        while(cur!=null){
            System.out.println(cur.data);
            cur=cur.next;
        }
    }


}
public class class1 {

    public static void main(String[] args) {
        linkstack t1=new  linkstack();
        for(int i=0;i<10;i++){
   t1.inserthead(i);

    }
        System.out.println("======原栈====");
        t1.show();
        t1.pop();
        System.out.println("=====出栈之后=====");
        t1.show();
        System.out.println("栈顶元素为"+t1.gettop());

}}

运行结果
======原栈====
9
8
7
6
5
4
3
2
1
0
=====出栈之后=====
8
7
6
5
4
3
2
1
0
栈顶元素为8

猜你喜欢

转载自blog.csdn.net/qq_37232304/article/details/80244009
今日推荐