链表中的结点是以结点来表示,单链表每一个结点有一个指针域和data域,物理位置不是连续的,逻辑上是连续的。
![b3110d4fff577a38b67e47156381dafe.png](https://i-blog.csdnimg.cn/blog_migrate/068333aca9ed43a5afd36056771d8451.jpeg)
代码实现
class LinkedList<E> {
private Node<E> head;
private Integer size;
public LinkedList(){
head = new Node<>(null,null);
size = 0;
}
//往链表末尾添加元素
public void add(E e){
Node<E> temp = head;
Node<E> newNode = new Node<>(e,null);
while (true){
if (temp.next == null){
break;
}
temp = temp.next;
}
temp.next = newNode;
size++;
}
//指定位置插入
public boolean insert(E e,int index){
if (index > size || index < 0){
throw new IndexOutOfBoundsException();
}
Node<E> temp = head;
Node<E> newNode = new Node<>(e,null);
for (int i = 0; i < index; i++){
temp = temp.next;
}
if (index != size){
newNode.next = temp.next;
}
temp.next = newNode;
size++;
return true;
}
//获取链表长度
public int size(){
return size;
}
//移除元素
public boolean remove(int index){
if (index > size){
throw new IndexOutOfBoundsException();
}
Node<E> temp = head;
for (int i = 0; i < index; i++){
temp = temp.next;
}
if (index == size){
temp.next = null;
return true;
}
temp.next = temp.next.next;
size--;
return true;
}
//展示所有元素
public boolean show(){
Node<E> temp = head;
while (temp.next != null){
System.out.println(temp.next.item);
temp = temp.next;
}
return true;
}
public boolean isEmpty(){
return size == 0;
}
//获取指定索引处的元素
public E get(int index){
if (isEmpty()){
throw new IndexOutOfBoundsException("链表为空");
}
if (index > size){
throw new IndexOutOfBoundsException();
}
Node<E> temp = head;
for (int i = 0; i < index - 1; i++){
temp = temp.next;
}
return (E) temp.next.item;
}
//节点
private static class Node<E>{
E item;
Node<E> next;
Node(E element,Node<E> next){
this.item = element;
this.next = next;
}
}
}
简单测试
public class LinkedListTest{
public static void main(String[] args) {
LinkedList<String> linkedList = new LinkedList<>();
linkedList.add("你好");
linkedList.add("世界");
linkedList.add("哈哈");
linkedList.insert("!",2);
linkedList.show();
System.out.println("----------------");
linkedList.remove(3);
linkedList.show();
}
}
运行结果
你好
世界
!
哈哈
----------------
你好
世界
!
欢迎关注我的微信公众号(秃头之路)