上篇文章中,我们主要介绍了遍历链表,求链表长度,是否包含关键字,头插法,接下来,我们将继续学习链表的方法,敬请期待叭~(这么可怜的up主,真的不关注一下嘛~)
1.尾插法
1.定义一个node节点
2.找到尾巴节点
3.插入
4.判断链表为空的情况
借图理解,请看
找到尾巴节点:cur.next == null,cur所指向的就是最后一个节点
插入元素:cur.next = node:即可 如图
如果为空,直接让head = node即可
代码如下
public void addLast(int data){
ListNode node = new ListNode(data);
ListNode cur = head;
if(cur == null) {
head = node;
return;
}
//找到链表的尾巴 注意是cur.next 不是cur
while (cur.next != null) {
cur = cur.next;
}
cur.next = node;
}
调用测试
public class test {
public static void main(String[] args) {
MySingleList mySingleList = new MySingleList();
mySingleList.createList();
mySingleList.display();
mySingleList.addLast(100);
mySingleList.display();
}
}
运行截图
2.任意位置插入
我们还是借助图来理解
1.我们先给链表编号,借助理解
2.如果要在2位置插入,要找到2前面的节点,进行修改插入
3.定义一个cur,让cur=index-1,即为2前面的节点
4.插入node.next = cur.next,cur.next = node
5.如果往头位置插入即为头插,在末尾即为尾插
6.判断位置是否合法 小于0和大于size
代码如下
public void addIndex(int index,int data){
if(index < 0 || index > size()) {
System.out.println("index 不合法");
return;
}
if(index == 0) {
addFirst(data);
return;
}
if(index == size()) {
addLast(data);
return;
}
ListNode cur = findIndexSubOne(index);
ListNode node = new ListNode(data);
node.next = cur.next;
cur.next = node;
}
调用测试
public class test {
public static void main(String[] args) {
MySingleList mySingleList = new MySingleList();
mySingleList.createList();
mySingleList.display();
mySingleList.addIndex(0,9);
mySingleList.addIndex(3,999);
mySingleList.addIndex(6,9999);
mySingleList.display();
}
}
运行截图
3.删除第一次出现的关键字key
即直接跳过要删除的节点
1.找到要删除节点的前一个节点,理论上同,这里就不多赘述
2.此时要删除的节点 del= cur.next
3.删除
cur.next = del.next
链表为空直接返回,并且要单独删除头节点(head = head.next;)
如图
代码如下
public void remove(int key){
if(head == null) {
return;
}
//单独删除头节点
if(head.val == key) {
head = head.next;
return;
}
ListNode cur = searchPrev(key);
if(cur == null) {
System.out.println("没有你要删除的数字");
return;
}
ListNode del = cur.next;
cur.next = del.next;
}
private ListNode searchPrev(int key) {
ListNode cur = head;
while (cur.next != null) {
if(cur.next.val == key) {
return cur;
}
cur = cur.next;
}
return null;
}
调用测试
public class test {
public static void main(String[] args) {
MySingleList mySingleList = new MySingleList();
mySingleList.createList();
mySingleList.display();
mySingleList.remove(23);
mySingleList.display();
}
}
结果截图
到此为止,我们本篇文章就结束啦,谢谢大家观看,下一篇我们将删除所有出现的key节点和清空链表,敬请期待叭~谢谢大家观看~