一、链表是什么?
链表是一种物理存储结构上非连续存储结构,数据元素的逻辑顺序是通过链表中的引用链接次序实现的 。
二、链表相关操作
1.创建链表
代码如下(示例):无头结点的单向链表创建
static class Node {
public int val; //存储的数据
public Node next; //存储下一个节点的地址
public Node(int val) {
this.val = val;
}
}
public Node head; // 当前列表的头节点
public void createLink() {
Node node1 = new Node(12);
Node node2 = new Node(22);
Node node3 = new Node(32);
Node node4 = new Node(42);
node1.next = node2;
node2.next = node3;
node3.next = node4;
head = node1; //head是头 ,指向了node1对象
} //创建列表
2.链表的相关操作
2.1 链表的遍历
代码如下(示例):
public void display() {
Node cru = head; //防止head走完 链表不知道头节点
while (cru != null) { //如果用的head.next !=null; 那么就会不打印尾节点的值
System.out.print(cru.val + " ");
cru = cru.next;
}
}
2.2 获取链表的长度
代码如下(示例):
public int size() {
int count = 0; //计数器
Node cru = head; //定义局部的cru对象遍历,以防止head头结点遍历完后影响后续链表操作
while (cru != null) {
count++;
cru = cru.next;
}
return count;
}
2.3 头插法插入元素
代码如下(示例):
public void addFirst(int data) {
Node node = new Node(data); //首先创建个节点
node.next = head; //将原来的头节点址给新创建的结点连接
head = node; //将新创建的结点设置为新的头结点
}
2.4 尾插法插入元素
代码如下(示例):(因其需要遍历寻找尾结点,较复杂于头插法)
public void addFinal(int data) {
Node node = new Node(data);
if (head == null) { //若头结点为空,则头尾相同,可直接将该结点插入
head = node;
return;
}
Node cru = head;
while (cru.next != null) { //一直遍历到找到尾结点
cru = cru.next;
}
cru.next = node;
}
2.5 任意位置的插入
代码如下(示例):
2.5.1 找到插入位置
//因为其为单向链表,需要先找到插入位置的前一个元素位置,后续进行插入操作
private Node findIndexSubone(int index) { //走到插入结点的前一位
Node cru = head;
int count = 0;
while (count != index - 1) {
cru = cru.next;
count++;
}
return cru;
}
2.5.2 检查位置的合法性
//需要先进行检查插入的位置是否合法,若不合法就抛出异常
private void checkIndex(int index) throws indexOutofException{
if (index < 0 || index > size()) {
throw new indexOutofException("index位置不合法");
}
};
public class indexOutofException extends RuntimeException{
public indexOutofException() {
}
public indexOutofException(String message) {
super(message);
}
}
2.5.3 进行插入操作
public void addIndex(int index, int data) throws indexOutofException{
checkIndex(index); //首先进行位置合法性的检查
if (index == 0) { //插入位置为头,直接头插法
addFirst(data);
return;
}
if (index == size()) { //插入位置为头,直接尾插法
addFinal(data);
return;
}
Node cru = findIndexSubone(index); //找寻插入位置的前一位
Node node = new Node(data);
node.next = cru.next; //进行插入操作
cru.next = node;
}
}
总结
本文介绍了单向链表的一些常见操作,用java实现了部分功能,对我们学习掌握数据结构很有帮助。