栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

创建的类——链表

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

创建的类——链表

package algorithm2;




import java.util.Iterator;

public class LinkList implements Iterable{


    //内部类
    private class Node{
        private T item;
        private Node next;
        public Node(T t,Node next) {
            this.item = t;
            this.next = next;
        }
    }
    //成员变量
    private Node head;
    private int N;
    //构造方法
    public LinkList(){
        //初始化头结点
        this.head = new Node(null,null);
        //初始化元素个数
        this.N = 0;
    }

    //成员方法
    //清空链表
    public void clear() {
        head.next = null;
        this.N = 0;
    }

    //获取链表长度
    public int length() {
        return N;
    }

    //判断链表是否为空
    public boolean isEmpty() {
        return N==0;
    }

    //获取指定位置i处的元素
    public T get(int i) {
        //通过循环,从头结点找i次,就可以找到元素
        Node n = head;
        for (int index = 0; index <=i;index ++) {
            n=n.next;
        }
        return n.item;
    }

    //向链表中插入元素
    public void insert(T t) {
        //找到当前链表的最后一个结点
        Node n = head;
        while(n.next!=null) {
            n=n.next;
        }
        //创建新节点
        Node node = new Node(t,null);
        //让当前最后一个结点指向新节点
        n.next = node;
        //元素的个数加1
        N++;
    }

    //在指定位置i处插入元素t;
    public void insert(int i,T t) {
        //找到i-1位置的结点
        Node n =head;
        for (int index = 0; index <= i-1; index++) {
            n=n.next;
        }
        //现在这个n是i-1位置的结点
        //创建一个新节点,指向i位置的结点
        Node newNode = new Node(t,n.next);
        //让i-1位置的结点指向新结点
        n.next = newNode;
        N++;
    }

    //删除i位置的结点,并返回删除的元素
    public T remove(int i) {
        Node n =head;
        //找到i-1位置的结点
        for (int index = 0; index <= i-1; index++) {
            n=n.next;
        }
        Node curr = n.next;
        Node xia = curr.next;
        n.next=xia;
        N--;
        return curr.item;
    }

    //查找某元素第一次出现的位置
    public int indexOf(T t) {
        Node n =head;
        for (int i =0; n.next != null; i++) {
            n=n.next;
            if (n.item==t) {
                return i;
            }
        }
        return -1;
    }

    @Override
    public Iterator iterator() {
        return new IteratorImpl();
    }
    private class IteratorImpl implements Iterator {
        //定义成员变量
        private Node n;
        int N;
        public IteratorImpl() {
            this.n=head;
            N=0;
        }
        @Override
        public boolean hasNext() {
            return n.next!=null;
        }

        @Override
        public Object next() {
            n=n.next;
            return n.item;
        }
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/950736.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号