模拟实现java集合类 LinkedList 及其主要方法get set remove size isEmpty contains

package com.qin.DataStructure;

public class LinkedList<E> {

    private class Node{
        public E e;
        public Node next;
        
		//构造函数
        public Node(E e, Node next){
            this.e = e;
            this.next = next;
        }
        public Node(E e){
            this(e,null);
        }
        public Node(){
            this(null,null);
        }
   }
    
       
// 全局变量
    private Node dummyHead;  	//虚拟头节点
    int size;

    public LinkedList() {
        dummyHead = new Node(null,null);
        size = 0;
    }

    public int getSize(){
        return size;
    }

    public boolean isEmpty(){
        return size == 0 ;
    }

    //在链表中间加入元素 e
    public void add(int index, E e){
        if(index < 0 || index > size){
            throw new IllegalArgumentException("Add failed. Illegal index!");
        }
        Node prev = dummyHead;
        for(int i = 0; i < index ; i++ ){
            prev = prev.next;    //找到索引处前一个点就好,因为加入了dummyHead所以要多加一次循环
        prev.next = new Node(e,prev.next);
        size++;
    }
    
    //获得链表的第index个位置的元素
    public E get(int index){
        if(index < 0 || index > size){
            throw new IllegalArgumentException("Add failed. Illegal index!");
        }
        Node current = dummyHead.next;
        for(int i = 0 ; i< index ; i++){
            current = current.next;      //第一个元素就是索引位0的,第二个是索引为1的,所以第index个,应该到index-1
        }
        return current.e;
    }
    
    public void set(int index, E e ){
        if(index < 0 || index > size){
            throw new IllegalArgumentException("Add failed. Illegal index!");
        }
        Node current = dummyHead.next;
        for(int i = 0 ; i<index ; i ++){
            current = current.next;
        }
        current.e = e;
    }
    //查找链表中是否有元素e
    public boolean contains(E e){
        Node current = dummyHead.next;
        while(current != null){
            if(current.e == e){
                return true;
            }
            current = current.next;
        }
        return false;
    }
    // 在链表中删除index(0-based)位置的元素,返回删除的元素
    // 在链表中不是一个常用的操作练习用
    public E remove(int index){
        if(index < 0 || index >= size){     //index = 0,就是第0个元素
            throw new IllegalArgumentException("Remove failed. Illegal index!");
        }
        Node prev = dummyHead;
        for(int i = 0; i < index ; i++){
            prev = prev.next;
        }
        Node del = prev.next;
        prev.next = del.next;
        del.next = null;
        size--;
        return del.e;
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值