• Java移除链表元素


    目录

    1.题目描述

    2.题解

    题解1

    题解2


    1.题目描述

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

    示例

    输入:head = [1,2,6,3,4,5,6],val = 6

    输出:[1,2,3,4,5]

    输入:head = [], val = 1
    输出:[]

    输入:head = [7,7,7,7], val = 7
    输出:[]

    2.题解

    题解1

    思路分析:创建新的链表,将链表中值不为val的节点尾插到新的节点中。

    利用cur遍历原来链表,tail遍历新的链表,若cur的值不为val,则将cur赋值给tail,cur向后移动,若cur的值为val,则跳过该节点。

    1. //创建新链表
    2. ListNode newHead = null;
    3. ListNode cur = head;
    4. ListNode tail = null;
    5. while(cur != null){
    6. if(cur.val != val) {
    7. //第一次插入
    8. if (tail == null) {
    9. newHead = tail = cur;
    10. } else {
    11. tail.next = cur;
    12. tail = cur;
    13. }
    14. }
    15. cur = cur.next;
    16. }

    由于tail的值可能不为空,此时我们需要将新链表的尾部置空

    1. //尾部置空
    2. if(tail != null){
    3. tail.next = null;
    4. }

    完整代码

    1. class Solution {
    2. public ListNode removeElements(ListNode head, int val) {
    3. //若链表为空,则直接返回null
    4. if(head == null){
    5. return null;
    6. }
    7. //创建新链表
    8. ListNode newHead = null;
    9. ListNode cur = head;
    10. ListNode tail = null;
    11. while(cur != null){
    12. if(cur.val != val) {
    13. //第一次插入
    14. if (tail == null) {
    15. newHead = tail = cur;
    16. } else {
    17. tail.next = cur;
    18. tail = cur;
    19. }
    20. }
    21. cur = cur.next;
    22. }
    23. //尾部置空
    24. if(tail != null){
    25. tail.next = null;
    26. }
    27. return newHead;
    28. }
    29. }

    题解2

    思路分析:要想删除链表中的元素,首先要找到值为val的节点node,将node的上一节点指向node的下一节点,即可删除值为val的节点,注意考虑头节点为val的情况,要删除链表中所有值为val的节点,利用while循环即可实现。

    由于链表为单链表,因此需要保存值为val节点node的上一个节点,可以创建prev和cur,cur指向当前节点,prev指向当前节点的上一节点,也可以通过cur.next.val找到值为val的节点

    1. ListNode cur = head;
    2. while(cur.next != null){
    3. if(cur.next.val == val){
    4. cur.next = cur.next.next;
    5. }else{
    6. cur = cur.next;
    7. }
    8. }

    当头节点的值也为val时,则需单独删除头节点

    1. if(head.val == val){
    2. head = head.next;
    3. }

    完整代码

    1. class Solution {
    2. public ListNode removeElements(ListNode head, int val) {
    3. //若链表为空,则直接返回null
    4. if(head == null){
    5. return null;
    6. }
    7. ListNode cur = head;
    8. while(cur.next != null){
    9. if(cur.next.val == val){
    10. cur.next = cur.next.next;
    11. }else{
    12. cur = cur.next;
    13. }
    14. }
    15. //单独考虑头节点的值是否等于val
    16. if(head.val == val){
    17. head = head.next;
    18. }
    19. return head;
    20. }
    21. }

    题目来源:

    203. 移除链表元素 - 力扣(LeetCode)

  • 相关阅读:
    数字信号处理——专栏说明篇
    【操作系统】聊聊页面置换算法
    前端面试宝典React篇02 为什么 React 要用 JSX?
    《MongoDB入门教程》第19篇 文档更新之$rename操作符
    Java两周半速成之路(第十天)
    【技巧】Win11 右键新建菜单没有文本文档选项
    合成复用原则~
    组合数学第四讲
    【牛客网面试必刷TOP101】链表篇(一)
    马来西亚考虑对TikTok电商实施禁令:定价和数据隐私问题浮出水面
  • 原文地址:https://blog.csdn.net/2301_76161469/article/details/133071093