代码随想录算法训练营第三天|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;
}
相关推荐
OTWOL25 分钟前
【C++编程入门基础(一)】
c++·算法
谏君之31 分钟前
C语言实现的常见算法示例
c语言·算法·排序算法
机器视觉知识推荐、就业指导1 小时前
【数字图像处理二】图像增强与空域处理
图像处理·人工智能·经验分享·算法·计算机视觉
IT猿手2 小时前
超多目标优化:基于导航变量的多目标粒子群优化算法(NMOPSO)的无人机三维路径规划,MATLAB代码
人工智能·算法·机器学习·matlab·无人机
Erik_LinX2 小时前
算法日记25:01背包(DFS->记忆化搜索->倒叙DP->顺序DP->空间优化)
算法·深度优先
Alidme2 小时前
cs106x-lecture14(Autumn 2017)-SPL实现
c++·学习·算法·codestepbystep·cs106x
小王努力学编程2 小时前
【算法与数据结构】单调队列
数据结构·c++·学习·算法·leetcode
最遥远的瞬间2 小时前
15-贪心算法
算法·贪心算法
万兴丶3 小时前
Unity 适用于单机游戏的红点系统(前缀树 | 数据结构 | 设计模式 | 算法 | 含源码)
数据结构·unity·设计模式·c#
维齐洛波奇特利(male)3 小时前
(动态规划 完全背包 **)leetcode279完全平方数
算法·动态规划