单向链表
来源:互联网 发布:淘宝 潘多拉哪家是真的 编辑:程序博客网 时间:2024/06/06 08:40
package 链表;import java.util.Iterator;public class SingleLink implements Iterable{ private int size; private Node first;//首节点 /** * * 节点内部类 * */ private class Node{ Object data; Node next; public Node(Object data,Node next){ this.data=data; this.next=next; } } /** * 根据指定索引查找节点 * @param index * @return */ private Node node(int index){ Node c=first; for(int i=0;i<index;i++){ c=c.next; } return c; } /** * 添加方法 * @param obj */ public void add(Object obj){ Node newNode=new Node(obj,null); if(first==null){ first=newNode; }else{ Node last=node(size-1); last.next=newNode; } size++; } public Object get(int index){ this.checkIndex(index); return node(index).data; } /** * 检查下标是否正确的方法 * @param index */ private void checkIndex(int index){ if(index<0){ throw new IndexOutOfBoundsException("is negative number! "+index); } if(index>=size){ throw new IndexOutOfBoundsException("index out of bounds "+index); } } /** * 返回大小的方法 * @return */ public int size(){ return size; } private class Iter implements Iterator{ private Node cNode=first; private int cursor=0;@Overridepublic boolean hasNext() {return cursor!=size;}@Overridepublic Object next() {Object o=cNode.data;cNode=cNode.next;cursor++;return o;} }@Overridepublic Iterator iterator() {return new Iter() ;}/** * 在指定位置插入一个新的节点 * @param obj */public void insert(Object obj,int index){this.checkIndex(index);if(index==0){Node newNode=new Node(obj,first);first=newNode;}else{Node target=node(index);Node newNode=new Node(obj,target);Node pre=node(index-1);pre.next=newNode;}size++;}/** * 删除指定位置节点 * @param index */public void delete(int index){this.checkIndex(index);Node target=node(index-1);target.next=target.next.next;size--;}}
0 0
- 单向链表
- 单向链表倒序
- 单向链表
- 单向链表逆转
- 逆转单向链表
- 单向链表反转
- 单向链表
- 单向链表(ZT)
- 反转单向链表
- 单向链表反转
- 单向链表
- 创建单向链表
- 单向链表反转
- 单向链表
- 单向链表
- 单向链表
- 单向链表
- C++ 单向链表
- 第十四周项目2数组大折腾(2)
- poj 1364
- MyBatis Generator 详细讲解
- Strcat、Strcpy、Strcmp、Strlen函数原型
- A - Matrix Game(nim 博弈)LightOJ 1247
- 单向链表
- Java中的ExceptionInInitializerError异常及解决方法
- IOS开发使用原生框架,二维码(条形码)的生成与扫描(支持长按扫描),可控制闪光灯
- 实例方法不能脱离对象引用
- 操作SELECT相关
- 双向链表
- 文章标题
- JavaScript中三元运算符
- ZOJ 1003 Crashing Balloon