代码随想录算法训练营第三天|203.移除链表元素、707.设计链表、206.反转链表

203.移除链表元素

给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。

解题思路

感觉这套题目算是入门题?我一开始用的for遍历,放在一个新的ListNode里面,也是可以正常AC的。但是如果要想到虚拟节点,就可能动点脑子了。

解法1
java 复制代码
public ListNode removeElements(ListNode head, int val) {
	if (head == null) {
		return head;
	}
	ListNode dummy =new ListNode(-1, head);
	ListNode pre = dummy;
	ListNode cur = head;
	while (cur != null) {
		if (cur.val == val) {
			pre.next = cur.next;
		} else {
			pre = cur;
		}
		cur = cur.next;
	}
	return dummy.next;
}

707.设计链表

你可以选择使用单链表或者双链表,设计并实现自己的链表。

解题思路

很难想到,或者说很难成体系的完成这类设计题目。需要时常学习或者复习。

解法1
java 复制代码
class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }
}

class MyLinkedList {
    int size;
    ListNode head;

    public MyLinkedList() {
        size = 0;
        head = new ListNode(0);
    }

    public int get(int index) {
        if (index < 0 || index >= size) {
            return -1;
        }
        ListNode cur = head;
        for (int i = 0; i <= index; i++) {
            cur = cur.next;
        }
        return cur.val;
    }

    public void addAtHead(int val) {
        addAtIndex(0, val);
    }

    public void addAtTail(int val) {
        addAtIndex(size, val);
    }

    public void addAtIndex(int index, int val) {
        if (index > size) {
            return;
        }
        if (index < 0) {
            index = 0;
        }
        size++;
        ListNode pre = head;
        for (int i = 0; i < index; i++) {
            pre = pre.next;
        }
        ListNode toAdd = new ListNode(val);
        toAdd.next = pre.next;
        pre.next = toAdd;
    }

    public void deleteAtIndex(int index) {
        if (index < 0 || index >= size) {
            return;
        }
        size--;
        if (index == 0) {
            head = head.next;
            return;
        }
        ListNode pre = head;
        for (int i = 0; i < index; i++) {
            pre = pre.next;
        }
        pre.next = pre.next.next;

    }
}

206.反转链表

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

解题思路

很老,但是考察也很多的题目。很经典。遍历和递归都要学会,这个需要看视频学习。

解法1
java 复制代码
public ListNode reverseList(ListNode head) {
	ListNode pre = null;
	ListNode cur = head;
	ListNode tmp = null;
	while (cur != null) {
		tmp = cur.next;
		cur.next = pre;
		pre = cur;
		cur = tmp;
	}
	return pre;
}
相关推荐
lisw051 小时前
互联网上的数据结构可视化!
数据结构·信息可视化
AiNightVision3 小时前
无人机夜视模块如何选择?——从参数指标到系统集成的完整选型指南
人工智能·算法·计算机视觉·车载系统·无人机·视频·智能硬件
牧羊人.3334 小时前
卷积神经网络之VGG
人工智能·深度学习·神经网络·算法·cnn
小郎君6584 小时前
Vue 多标签页的加载态设计:为什么我没有用 Suspense 实现 PageLoading
vue.js·算法
JJJennie7775 小时前
MAI Gateway私有化部署全攻略:大模型网关如何接入?附架构图
算法·gateway·ai网关·魔芋ai
東隅已逝,桑榆非晚5 小时前
算法3.双指针法-快乐数
c++·笔记·学习·算法
专注仿真5 小时前
卷积神经网络(CNN)算法详解
人工智能·python·算法·代码·大模型训练
FII工业富联科技服务5 小时前
多智能体如何进入制造现场?从业务协同到数字孪生验证
大数据·人工智能·算法·机器人·制造·数字孪生
≮傷£≯√5 小时前
httpserver_QNetWorkClient
算法
Evand J5 小时前
【PMSM例程11】永磁同步电机(PMSM)基于UKF的转速与转子位置估计。附下载链接
算法·matlab·卡尔曼滤波·永磁同步电机·ukf·pmsm·位置估计