JAVA泛型實現一個堆棧類

來源:互聯網
上載者:User

標籤:

 1 package com.xt.test; 2  3 /** 4  * 泛型實現堆棧,thinking in java中的例子 5  *  6  * @author Administrator 7  * 8  * @param <T> 9  */10 public class LinkedTrack<T> {11     private static class Node<U> {12         U item;13         Node<U> next;14 15         Node() {16             item = null;17             next = null;18         }19 20         Node(U item, Node<U> next) {21             this.item = item;22             this.next = next;23         }24 25         boolean end() {26             return item == null && next == null;27         }28     }29 30     /**31      * 末端哨兵,用來標示是否到了盡頭32      */33     private Node<T> top = new Node<T>();34 35     /**36      * 節點中添加節點(包含進去)37      * 38      * @param item39      */40     public void push(T item) {41         top = new Node<T>(item, top);42     }43 44     /**45      * 節點中取節點(捨去)46      * 47      * @return48      */49     public T pop() {50         T result = top.item;51         if (!top.end())52             top = top.next;53         return result;54     }55 56     public static void main(String[] args) {57         LinkedTrack<String> lt = new LinkedTrack<String>();58         for (String s : "This is a test!".split(" "))59             lt.push(s);60         String s;61         while ((s = lt.pop()) != null)62             System.out.println(s);63     }64 65 }

看書中的代碼看了很久都搞不懂到底是怎麼實現的,最終在eclipse中把代碼照著寫了一邊,人笨,調試運行才恍然大悟原來用來<多層嵌套的原理>(自己瞎想的名字),具體看如下:

 

JAVA泛型實現一個堆棧類

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.