Java手写一个链表的数据结构
最近开始复习数据结构和算法,记录一下
链表是平时开发中也很常遇到的,为了加强自身基础,吾最近开始复习数据结构和算法,下面使用Java实现一个单向的链表记录一下。
为什么说是单向的呢,因为链表有很多的种类,单向链表,双向链表,循环链表等。后续再学习。
代码如下:
/**
* 实现链表的数据结构.
*
* @author lzp
* @version 1.0.0
* @date 2020/12/30 15:59
*/
public class LinkListStructure {
/**
* 当前链表头节点.
*/
private Node head;
/**
* 当前链表尾节点.
*/
private Node last;
/**
* 当前链表大小.
*/
private int size;
/**
* 向链表插入元素.
*
* @param data
* @param index
*/
public void insert(int data, int index) {
if (index > size || index < 0) {
throw new IndexOutOfBoundsException("下标非法");
}
Node insertNode = new Node(data);
//链表为空
if (size == 0) {
head = insertNode;
last = insertNode;
} else if (index == 0) {
//头插法
insertNode.next = head;
head = insertNode;
} else if (index == size) {
//尾部插入
last.next = insertNode;
last = insertNode;
} else {
//中间插入
Node pre = get(index - 1);
insertNode.next = pre.next;
pre.next = insertNode;
}
size++;
}
/**
* 获取指定下标的链表节点.
*
* @param index
* @return
*/
public Node get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("超出范围!");
}
Node temp = head;
for (int i = 0; i < index; i++) {
temp = temp.next;
}
return temp;
}
/**
* 删除指定位置的元素.
*
* @param index
*/
public void delete(int index) {
if (index < 0 || index > size || size == 0) {
throw new IndexOutOfBoundsException("超出范围!");
}
if (index == 0) {
//从头部删除
head = head.next;
} else if (index == size - 1) {
//从尾部删除
Node node = get(size - 1);
node.next = null;
last = node;
} else {
//从中间删除
Node pre = get(index - 1);
Node next = pre.next.next;
pre.next = next;
}
size--;
}
/**
* 打印链表.
*/
public void tostring() {
if (size <= 0) {
throw new IndexOutOfBoundsException("数据为空!");
}
Node temp = head;
for (int i = 0; i < size; i++) {
System.out.print(temp.data);
if (temp.next != null) {
System.out.print("-->");
}
temp = temp.next;
}
System.out.println();
}
/**
* 链表节点数据结构.
*/
private static class Node {
int data;
Node next;
Node(int data) {
this.data = data;
}
}
public static void main(String[] args) {
LinkListStructure list = new LinkListStructure();
//插入1、2
list.insert(1, 0);
list.insert(2, list.size);
list.tostring();
//头部插入5
list.insert(5, 0);
list.tostring();
//中间插入4
list.insert(4, 2);
list.tostring();
//删除指定元素
list.delete(2);
list.tostring();
list.delete(0);
list.tostring();
}
}
输出的结果:
1–>2
5–>1–>2
5–>1–>4–>2
5–>1–>2
1–>2
以上代码,基本实现了链表结构的增删改查,后续将基于此链表来讨论一个Java新手在开发中容易出现的问题~