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;
}
}
模拟实现java集合类 LinkedList 及其主要方法get set remove size isEmpty contains
最新推荐文章于 2020-09-19 15:34:26 发布