【Leetcode刷题篇】leetcode203 移除链表元素
发布日期:2021-06-29 15:32:56 浏览次数:2 分类:技术文章

本文共 615 字,大约阅读时间需要 2 分钟。

题解:删除链表中等于给定值 val 的所有节点。

示例:

输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5

解题思路:定义两个指针来解题

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode first = new ListNode(-1); first.next = head; // 定义两个指针 ListNode pre = first; ListNode cur = head; while(cur!=null) {
if(cur.val==val) {
pre.next = cur.next; cur = cur.next; continue; } pre = pre.next; cur = cur.next; } return first.next; }}

转载地址:https://codingchaozhang.blog.csdn.net/article/details/109346916 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:【Leetcode刷题篇】leetcode83 删除排序链表中的重复元素
下一篇:【Leetcode刷题篇】leetcode141环形链表

发表评论

最新留言

能坚持,总会有不一样的收获!
[***.219.124.196]2024年04月19日 01时42分14秒