链表
链表是一种链式存取的数据结构,单链表中的数据是以结点的形式存在,每一个结点是由数据元素和下一个结点的存储的位置组成。单链表与数组相比的最大差别是:单链表的数据元素存放在内存空间的地址是不连续的,而数组的数据元素存放的地址在内存空间中是连续的,这也是为什么根据索引无法像数组那样直接就能查询到数据元素。
结点类
public class Node {
Object data;
Node next;
}
链表操作
public class MyLinked {
//存储头结点对象
private Node head = new Node();
/**
* 在链表中添加结点
*
* @param data 要添加的结点
*/
public void append(Object data) {
//创建一个指针变量,用来遍历当前链表,该指针从头结点开始
Node current = head;
//遍历链表,直到该结点的地址为null
while (current.next != null) {
//将指针的地址赋值给指针
current = current.next;
}
//将追加的元素封装在一个新的结点中。
Node node = new Node();
node.data = data;
//将临时变量指向最后一个结点,将新建结点添加到链表末尾
current.next = node;
}
/**
* 遍历链表
*/
public void iterate() {
//定义 指针,遍历链表
Node current = head;
while (current.next != null) {
current = current.next;
System.out.print(current.data + " ");
}
}
/**
* 向链表中指定位置插入数据
*
* @param data 要插入的数据
* @param index 插入的位置
*/
public void insert(Object data, int index) {
//创建计数器,用来确定插入位置
int step = 0;
//创建指针,遍历链表
Node current = head;
//循环确定要插入的位置
while (step < index) {
current = current.next;
step++;
}
//创建新的结点,封装数据
Node node = new Node();
//为新的结点数据域赋值
node.data = data;
//将下一节点赋值给新节点的地址域
node.next = current.next;
//将新节点赋值给上一结点的地址域
current.next = node;
}
/**
* 按照下标返回链表中的数据元素
*
* @param index 下标
*/
public Object get(int index) {
//创建计数器,确定元素位置
int step = 0;
//创建指针,遍历链表
Node current = head;
//移动指针,确定要查找的结点
while (step < index + 1) {
current = current.next;
step++;
}
return current.data;
}
/**
* 删除指定位置的元素
*
* @param index 指定的下标
*/
public void remove(int index) {
//创建计数器,确定要删除的位置
int step = 0;
//创建指针,遍历数组
Node current = head;
//确定要删除的位置
while (step < index) {
current = current.next;
step++;
}
//删除元素
current.next = current.next.next;
}
}
本文介绍了单链表的基本概念及其实现方式,包括结点类的定义、链表的添加、遍历、插入、获取指定位置元素及删除指定位置元素等核心操作。
3555

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



