动画讲解链表3大基本操作 - 插入,删除与翻转

链表是一种时常会用到的数据结构,因此扎实掌握链表的基本操作则显得十分重要。

以下是关于几个常见链表操作的动态图解,大家可以收藏起来,方便以后复习之用。

链表插入

插入空链表

在这里插入图片描述

Node newNode = newNode(data);
head = newNode;
newNode.next = null;

插入链表中央

在这里插入图片描述

Node newNode = new Node(data);
Node current = head;
// 遍历寻找插入位置
while (!current.equals(targetNode)) {
	current = current.next;
}
newNode.next = current.next;
current.next = newNode;

插入链表开头

在这里插入图片描述

Node newNode = new Node(data);
newNode.next = head;
head = newNode;

插入链表末尾

在这里插入图片描述

Node newNode = new Node(data);
Node current = head;
// 遍历到链表末尾
while (current.next != null) {
	current = current.next;
}
current.next = newNode;
newNode.next = null;

链表删除

删除中间节点

在这里插入图片描述

Node prev = null;
Node current = head;
// 遍历寻找目标节点
while (!currentNode.equals(targetNode)) {
	prev = current;
	current = current.next;
}
prev.next = current.next;

删除头节点

在这里插入图片描述

head = head.next;

删除末尾节点

在这里插入图片描述
同删除中间节点代码一样

Node prev = null;
Node current = head;
// 遍历寻找目标节点
while (!currentNode.equals(targetNode)) {
	prev = current;
	current = current.next;
}
prev.next = current.next;

翻转链表

在这里插入图片描述

public class Main {
	public static void reverseLinkedList(LinkedList list) {
	    if (list.head == null ||  list.head.next == null) {
	        return;
	    }
	
	    Node prev = null;
	    Node current = list.head;
	    Node next = current.next;
	
	    while (current != null) {
	        current.next = prev;
	        if (next == null) {
	            break;
	        }
	        prev = current;
	        current = next;
	        next = next.next;
	    }
	    list.head = current;
	}
}

class Node {
    public Node next;
    public int val;

    public Node(int val) {
        this.val = val;
        this.next = null;
    }
}

class LinkedList {
    public Node head;
}
  • 2
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值