简单_单链表


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() {
}
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值