简介
单链表在逻辑上是线性的,在存储结构是却不是连续的,单链表同其名字一样为单向,单链表在数据结构中也算一种比较基础简单的结构
Java 实现
逻辑思路
单链表只有一个方向,单链表逻辑上是线性的,链表中靠一个个的结点连接起来的,链表中存有数据和下一个结点的地址,单链表快在插入和删除上,对于从尾部添加和查找第几个元素会比较慢,对于插入的实现,将新结点指向单链表中的一个结点,然后断开链表中的这个结点和前一个结点的连接,让前一个结点指向插入的结点即可,对于删除的实现是直接让单链表中的一个结点指向下下个结点即可,新增结点的实现是遍历到最后一个再新增,对于查找的实现是直接遍历去寻找
算法图解
代码实现
// 单链表结点
class Node {
int data;
Node next = null;
}
// 单链表
public class SinglyLinkedList {
// 头结点
private Node head;
// 初始化
public SinglyLinkedList() {
head = null;
}
// 头插法创建单链表(倒序)
public Node createFromHead(int[] arr) {
for (int i = 0; i < arr.length; i++) {
Node node = new Node();
node.data = arr[i];
node.next = head.next;
head.next = node;
}
return head;
}
// 尾插法创建单链表(顺序)
public Node createFromTail(int[] arr) {
Node h = head;
for (int i = 0; i < arr.length; i++) {
Node node = new Node()
node.data = arr[i];
node.next = null;
h.next = node;
h = node;
}
return head;
}
// 单链表新增数据
public Node add(Node n) {
Node h;
for (h = head; h.next != null; h = h.next);
h.next = n;
return head;
}
// 查找数据
public int search(int num) throws Exception {
int k = 0;
for (Node h = head; h.next != null; k++,h = h.next);
if (num < 1 || num > k)
throw new Exception("数字超过范围!");
Node h = head;
for (int i = 1; i <= num; i++,h = h.next);
return h.data;
}
// 插入数据,其他数据后移
public Node insert(int num, Node n) throws Exception {
int k = 0;
for (Node h = head; h.next != null; k++,h = h.next);
if (num < 1 || num > k)
throw new Exception("数字超过范围!");
Node h = head;
for (int i = 1; i < num; i++,h = h.next);
n.next = h.next;
h.next = n;
return head;
}
// 删除数据
public int delete(int num) throws Exception {
int k = 0;
for (Node h = head; h.next != null; k++,h = h.next);
if (num < 1 || num > k)
throw new Exception("数字超过范围!");
Node h = head;
for (int i = 1; i < num; i++,h = h.next);
int e = (h.next).data;
h.next = (h.next).next;
return e;
}
}
7532

被折叠的 条评论
为什么被折叠?



