自定义StringLinkedList

简单字符串链表结构

提供从链表头部新增元素,删除元素、判断元素是否在链表中、链表元素个数、以及从链表头部开始打印所有元素(新添加元素先打印)、toArray方法。

public class StringLinkedList {
    //构造链表结构
    private NodeList head;
    public StringLinkedList() {
        this.head = null;
    }

    /**
     * 从链表头部添加一个元素
     * @param data
     */
    public void addToStart(String data){
        NodeList position = head;
        head = new NodeList(data,position);
    }

    /**
     * 从头部删除一个元素,后添加的先删除
     */
    public void deleteFromStart(){
        NodeList position = head;
        if(position != null){
            head = position.link;
        }else{
            //所有元素都已经删除
            System.out.println("all deleted");
        }
    }

    /**
     * 打印链表中的所有元素,从第一个开始,即后添加的先打印
     */
    public void printAll(){
        NodeList position = head;
        while (position != null){
            System.out.println(position.date);
            position = position.link;
        }
    }

    /**
     * 返回当前链表的元素个数
     * @return int 元素个数
     */
    public int length() {
        NodeList position = head;
        int count = 0;
        while (position != null){
            count ++;
            position = position.link;
        }
        return count;
    }

    /**
     * 判断当前元素是否在链表中
     * @param date
     * @return fasle 代表不在,true 代表在
     */
    public boolean onStringLinkedList(String date){
        return find(date) != null;
    }

    public NodeList find(String date) {
        NodeList position = head;
        while (position != null) {
            if(position.date.equals(date)){
                return position;
            }
            position = position.link;
        }
        return null;
    }

    /**
     * 转字符串数组
     * @return
     */
    public String[] toArray(){
        String [] array = new String[length()];
        NodeList position = head;
        int i = 0;
        while (position != null){
            array[i] = position.date;
            i++;
            position = position.link;
        }
        return array;
    }

    //内部类NodeList,内外类变量可直接访问
    private class NodeList{
        private String date;
        //将类类型作为实例变量构造链表结构中指向下一个节点的引用
        private NodeList link;
        //提供两个构造方法
        public NodeList() {
            this.date = null;
            this.link = null;
        }
        public NodeList(String date, NodeList link) {
            this.date = date;
            this.link = link;
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值