链表和数组同属于线性结构,他与数组是互补的。数组属于静态存储结构,而链表属于动态存储结构。
链表是逻辑上连续的存储单元,但物理上不连续。链表的基本存储单元是节点(node),存储单元之间使用引用或指针相互链接。同一个数组只能存储同种数据类型的元素,链表也一样,同一个链表只能存储同种数据类型。链表可以为空。链表的第一个节点称为头节点,最后一个节点称为尾节点,当链表为空时,头节点和尾节点相同,都指向null。
太懒了,不想写注释,直接给你们看老师的吧
//测试类
public class TestSingleList {
public static void main(String[] args) {
SingleList.addTail(100);
SingleList.addTail(1000);
System.out.println("size : " + SingleList.size);
}
}
//单链表数据模型类
class SingleList {
//头节点
static Node first = null;
//尾节点
static Node last = null;
//节点数
static int size = 0;
//添加-尾部
//value表示要存入节点数据域的值。
public static void addTail(int value) {
//创建一个节点
Node newNode = new Node();
newNode.data = value;
if (last == null) {
first = newNode;
last = newNode;
} else {
last.next = newNode;
last = newNode;
}
size++;
}
//添加-头部
public static void addFirst(int value) {
//创建一个节点
Node newNode = new Node();
newNode.data = value;
if(first == null) {
first = newNode;
last = newNode;
} else {
newNode.next = first;
first = newNode;
}
siez++;
}
//删除,position表示要删除的是第几个节点
public static void remove(int position) {
//记录当前访问到了第几个节点
int count = 1;
//变量指向当前节点的上一个节点
Node preCurrent = null;
//定义变量指向需要查找的当前节点
Node current = first;
while(current != null) {
//当删除的是第一个节点时
if (position == 1) {
first = first.next;
current.next = null;
return;
} else if(position == count) {
System.out.println("执行删除");
preCurrent.next = current.next;
current.next = null;//断掉引用
return;
} else {
preCurrent = current;
current = current.next;
}
count++;
}
}
//更新, 把指定位置position的值更新为新的值newVal
public static void update(int position, int newVal){
Node node = get(position);
node.data = newVal;
}
//查找,按照位置访问
public static Node get(int position){
int count = 1;
Node t = first;
while(t != null) {
if (position == count) {
System.out.println(t.data);
return t;
}
t = t.next;
count++;
}
return null;
}
//查看链表中是否包含指定的值val
public static void containes(int val){}
//反转
public static void reverseList(){}
//在指定位置插入一个节点
public static void insert(int position, int value) {}
//遍历链表
public static void traverse() {
//定义一个临时变量用于获取节点的数据
Node t = first;
while(t != null) {
System.out.println(t.data);
t = t.next;
}
}
}
//节点类
class Node {
int data;
Node next;
}
评论 (0)