底层结构为链表;
- import java.util.Iterator;
- //LinkedLink其实是双向链表
- public class MyLinkedList<E> implements Iterable<E>{
- int size;
- private Node head=null;//头部节点
- private Node tail=null;//尾部节点
- public void add(E e){
- Node node=new Node(e,null);
- if(head==null){
- head=node;
- tail=node;
- }else{
- tail.setNext(node);
- tail=node;
- }
- size++;
- }
- public int getSize(){
- return size;
- }
- public Iterator<E> iterator() {
- return new Iterator<E>(){
- Node temp=head;
- public boolean hasNext() {
- return temp!=null;
- }
- public E next() {
- E data=temp.data;
- temp=temp.next;
- return data;
- }
- public void remove() {
- }};
- }
- class Node{//内部类,节点
- private E data;
- private Node next;
- public Node(E data, Node next) {
- super();
- this.data = data;
- this.next = next;
- }
- public E getData() {
- return data;
- }
- public void setData(E data) {
- this.data = data;
- }
- public Node getNext() {
- return next;
- }
- public void setNext(Node next) {
- this.next = next;
- }
- }
- }
- public class Test2 {
- public static void main(String[] args) {
- MyLinkedList<String> mylink=new MyLinkedList<String>();
- mylink.add("a");
- mylink.add("v");
- mylink.add("vw");
- System.out.println("元素个数:"+mylink.getSize());
- for(String data:mylink){
- System.out.println(data);
- }
- }
- /**
- 元素个数:3
- a
- v
- vw
- */
- }