首页 / JAVA / Java手写一个链表的数据结构
Java手写一个链表的数据结构
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Java手写一个链表的数据结构,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2544字,纯文字阅读大概需要4分钟。
内容图文
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新手在开发中容易出现的问题~
内容总结
以上是互联网集市为您收集整理的Java手写一个链表的数据结构全部内容,希望文章能够帮你解决Java手写一个链表的数据结构所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。