容易_单链表
简单_单链表
package sunfa; import java.util.Iterator; /** * 单链表 * * @author Administrator * */ public class SingleLinkedList { public static void main(String[] args) { SingleLinkedList link = new SingleLinkedList(); for (int i = 10; i < 20; i++) { link.add(i); } System.out.println("list:"); Iterator it = link.iterator(); while (it.hasNext()) { System.out.println(it.next()); } System.out.println("getFirst:" + link.getFirst()); System.out.println("getLast:" + link.getLast()); link.remove(13); link.remove(17); System.out.println("删除后"); it = link.iterator(); while (it.hasNext()) { System.out.println(it.next()); } } private Node head = new Node(null, null); private Node tail = null; public SingleLinkedList() { head.next = tail; } public Object getFirst() { if (head.next != null) return head.next.element; return null; } public Object getLast() { if (tail == null) { return null; } return tail.getElement(); } public void add(Object o) { Node node = new Node(o, null); if (tail == null) head.next = node; else tail.next = node; tail = node; } public Object remove(Object o) { for (Node e = head.next; e != head;) { Node current = e; e = e.next; if (e.element == o) { current.next = e.next; return e.element; } } return null; } // public Object find(int index){ // if(tail==null){ // return null; // } // while(index!=head.next.o){ // // } // } public Iterator iterator() { return new Itr(head); } private static class Node { Object element; Node next; public Node(Object o, Node next) { super(); this.element = o; this.next = next; } public Object getElement() { return element; } } private class Itr implements Iterator { private Node cur; public Itr(Node cur) { super(); this.cur = cur; } public boolean hasNext() { return cur.next != null; } public Object next() { Object o = cur.next.element; cur = cur.next; return o; } public void remove() { } } }