单向链表

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;
			@Override
			public boolean hasNext() {
				return cursor!=size;
			}
			@Override
			public Object next() {
				Object o=cNode.data;
				cNode=cNode.next;
				cursor++;
				return o;
			}
        }
		@Override
		public 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值