最基础的数组结构

最基础的数据结构

最基础的数据结构,不要小瞧数组

一、数组

/*
 * 动态数组   ,只需要修改下添加和删除操作
 * 		添加元素时:当size == capacity 时,扩容
 * 		删除元素时:当size == capacity/4时 ,缩容
 */
public class Array<E> {
	private E[] data;
	
	private int capacity; //容量
	
	private int size ;	//数据元素个数
	
	public Array(){
		this(10); //默认 10个为初始大小
	}
	
	public Array(int capacity) {
		this.data = (E[]) new Object[capacity];  //记住这种写法,
		this.size = 0 ;
		this.capacity = capacity;
	}
	//动态设置容量
	public void resize(int capacity) {
		E[] newdata = (E[])new Object[capacity];
		for(int i = 0 ;i < size;i++) {
			 newdata[i] = data[i];
		}
		data = newdata;
		this.capacity = capacity;  //维护之前的容量值
	}
	// 获取数组的容量getCapacity()
	public int getCapacity() {
		return capacity;
	}
	
	
	// 获取数组中的元素个数getSize()
	public  int getSize() {
		return size;
	}
	// 返回数组是否为空isEmpty()
	public boolean isEmpty() {
		return size == 0;
	}
	// 在index索引的位置插入一个新元素e add(int index, E e)
	public E add(int index , E e) {
		if(index < 0 || index > size ) {
			throw new RuntimeException("插入失败,索引越界异常");
		}
		if(size == capacity) {
			resize(2*data.length); //动态扩容
		}
		for(int i = size-1 ; i >= index ; i--) {
			data[i+1] = data[i];
		}
		data[index] = e;
		size++ ;  //别忘了维护元素个数
		return e;
	}
	 // 向所有元素后添加一个新元素 addLast(E e)
	public void addLast(E e) {
		add(size, e);
	}
	 // 在所有元素前添加一个新元素 addFirst(E e)
	public void addFirst(E e) {
		add(0, e);
	}
	// 获取index索引位置的元素 get(int index)
	public E get(int index) {
		if(index < 0 || index > size) {
			throw new IllegalArgumentException("索引不合理");
		}
		return data[index];
	}
	// 修改index索引位置的元素为e  set(int index, E e)
	public void  set(int index,E e) {
		if(index < 0 || index > size) {
			throw new IllegalArgumentException("索引不合理");
		}
		data[index] = e;
	}
	// 查找数组中是否有元素e contains(E e)
	public boolean contains(E e) {
		for (int i = 0; i < size; i++) {
			if(data[i].equals(e)) {
				return true;
			}
		}
		return false;
	}
	 // 查找数组中元素e所在的索引,如果不存在元素e,则返回-1 findElementIndex(E e)
	public int findElementIndex(E e) {
		for (int i = 0; i < size; i++) {
			if(data[i].equals(e)) {
				return i;
			}
		}
		return -1;
	}
	// 从数组中删除index位置的元素, 返回删除的元素  removeByIndex(int index)
	public E removeByIndex(int index) {
		if(index < 0 || index >= size)
            throw new IllegalArgumentException("Remove failed. Index is illegal.");

        E ret = data[index];
        for(int i = index + 1 ; i < size ; i ++)
            data[i - 1] = data[i];
        size --;
        data[size] = null; // loitering objects != memory leak
        
        if(size <= capacity/4) {
        	resize(capacity/2);   //删除后 元素个数小于等于原容量1/4 就缩容
        }
        
        return ret;
	}
	
	// 从数组中删除第一个元素, 返回删除的元素  removeFirst()
	public E removeFirst() {
		return removeByIndex(0);
	}
	// 从数组中删除最后一个元素, 返回删除的元素 removeLast()
	public E removeLast() {
		return removeByIndex(size-1);
	}
	 // 从数组中删除元素e removeElement(E e)
	public void removeElement(E e) {
		for (int i = 0; i < size; i++) {
			while(data[i].equals(e)) {
				for(int j = i ;j<=size-1;j++) {
					data[j] = data[j+1];
				}
				size--;
			}
		}
		if(size <= capacity/4) {
        	resize(capacity/2);   //删除后 元素个数小于等于原容量1/4 就缩容
        }
		
	}

	@Override
	public String toString() {
		return "Array [data=" + Arrays.toString(data) + ", capacity=" + capacity + ", size=" + size + "]";
	}
		
}

二、链表

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);
        }

        @Override
        public String toString(){
            return e.toString();
        }
    }
	
	private Node dummyHead;
	
	private int size;
	
	public LinkedList() {
		dummyHead = new Node();
		size = 0 ;
	}
	
	 // 获取链表中的元素个数
    public int getSize(){
        return size;
    }

    // 返回链表是否为空
    public boolean isEmpty(){
        return size == 0;
    }

    // 在链表的index(0-based)位置添加新的元素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;

        prev.next = new Node(e, prev.next);
        size ++;
    }

    // 在链表头添加新的元素e
    public void addFirst(E e){
        add(0, e);
    }

    // 在链表末尾添加新的元素e
    public void addLast(E e){
        add(size, e);
    }

    // 获得链表的第index(0-based)个位置的元素
    // 在链表中不是一个常用的操作,练习用:)
    public E get(int index){

        if(index < 0 || index >= size)
            throw new IllegalArgumentException("Get failed. Illegal index.");

        Node cur = dummyHead.next;
        for(int i = 0 ; i < index ; i ++)
            cur = cur.next;
        return cur.e;
    }

    // 获得链表的第一个元素
    public E getFirst(){
        return get(0);
    }

    // 获得链表的最后一个元素
    public E getLast(){
        return get(size - 1);
    }

    // 修改链表的第index(0-based)个位置的元素为e
    // 在链表中不是一个常用的操作,练习用:)
    public void set(int index, E e){
        if(index < 0 || index >= size)
            throw new IllegalArgumentException("Set failed. Illegal index.");

        Node cur = dummyHead.next;
        for(int i = 0 ; i < index ; i ++)
            cur = cur.next;
        cur.e = e;
    }

    // 查找链表中是否有元素e
    public boolean contains(E e){
        Node cur = dummyHead.next;
        while(cur != null){
            if(cur.e.equals(e))
                return true;
            cur = cur.next;
        }
        return false;
    }

    // 从链表中删除index(0-based)位置的元素, 返回删除的元素
    // 在链表中不是一个常用的操作,练习用:)
    public E remove(int index){
        if(index < 0 || index >= size)
            throw new IllegalArgumentException("Remove failed. Index is illegal.");

        Node prev = dummyHead;
        for(int i = 0 ; i < index ; i ++)
            prev = prev.next;

        Node retNode = prev.next;
        prev.next = retNode.next;
        retNode.next = null;
        size --;

        return retNode.e;
    }

    // 从链表中删除第一个元素, 返回删除的元素
    public E removeFirst(){
        return remove(0);
    }

    // 从链表中删除最后一个元素, 返回删除的元素
    public E removeLast(){
        return remove(size - 1);
    }

    // 从链表中删除元素e
    public void removeElement(E e){

        Node prev = dummyHead;  //初始化工作节点
        
        while(prev.next != null) {
        	while(prev.next != null && prev.next.e.equals(e)) { //删除连续的
        		Node delNode = prev.next;
        		prev.next = delNode.next;
        		delNode.next = null;
        		size--;
        	}
        	
        	if(prev.next == null) {
        		break;
        	}else {
				prev = prev.next;
			}
        }
        
    }
    //链表递归写法
    public ListNode removeElements_Recursion(ListNode head, int val) {
		if(head == null) {
			return null;
		}
		ListNode res = removeElements_Recursion(head.next, val);
		if(head.val == val) {
			return res;
		}else {
			head.next = res;
			return head;
		}
		
	}

    @Override
    public String toString(){
        StringBuilder res = new StringBuilder();

        Node cur = dummyHead.next;
        while(cur != null){
            res.append(cur + "->");
            cur = cur.next;
        }
        res.append("NULL");

        return res.toString();
    }
    
}
原文地址:https://www.cnblogs.com/Qvolcano-blog/p/14571025.html