尾插法实现LinkedList

来源:互联网 发布:机械行业推广优化方案 编辑:程序博客网 时间:2024/06/02 00:37

本科时学习数据结构一直是使用c语言,最近想到使用java实现尾插法链表会是什么样的效果呢,于是编写了一个简单的尾插法LinkedList,实现了迭代器,增加,删除,插入。供参考:

import java.util.Iterator;/** * Created by wzy on 17-2-24. */public class MyLinkedList<T> implements Iterable<T>{    public static class Node<U>{        U item;        Node<U> next;        public Node(){            item = null;            next = null;        }        public Node(U item, Node<U> next){            this.item = item;            this.next = next;        }    }    private Node<T> top = new Node<T>();    private Node<T> node = top;    public void add(T item){        node.next = new Node<T>(item, null);        node = node.next;    }    public void insert(int index, T item){        int i = -1;        Node<T> pre = null;        Node<T> now = null;        now = top;        while(i < index){            pre = now;            now = now.next;            i++;            if (i > index && now == null){                throw new RuntimeException("index error");            }        }        pre.next = new Node<T>(item, now);    }    public void remove(int index){        int i = -1;        Node<T> pre = null;        Node<T> now = null;        now = top;        while(i < index){            pre = now;            now = now.next;            i++;            if (i > index && now == null){                throw new RuntimeException("index error");            }        }        pre.next = now.next;    }    @Override    public Iterator<T> iterator() {        return new Iterator<T>() {            Node<T> now = top;            @Override            public boolean hasNext() {                return now.next != null;            }            @Override            public T next() {                now = now.next;                return now.item;            }        };    }    @Override    public String toString() {        StringBuffer stringBuffer = new StringBuffer("{");        node = top.next;        while(node != null){            stringBuffer.append(node.item + ", ");            node = node.next;        }        stringBuffer.delete(stringBuffer.length() -2 , stringBuffer.length());        stringBuffer.append("}");        return stringBuffer.toString();    }    public static void main(String[] args) {        MyLinkedList<String> list = new MyLinkedList<>();        list.add("1");        list.add("2");        list.add("3");        System.out.println(list);        list.insert(1, "4");        list.insert(4, "5");        System.out.println(list);        list.remove(4);        System.out.println(list);        for (String s : list){            System.out.println(s);        }    }/*output:{1, 2, 3}{1, 4, 2, 3, 5}{1, 4, 2, 3}1423*/}




0 0