zoukankan      html  css  js  c++  java
  • LeetCode–删除链表的节点

    LeetCode–删除链表的节点

    博客说明

    文章所涉及的资料来自互联网整理和个人总结,意在于个人学习和经验汇总,如有什么地方侵权,请联系本人删除,谢谢!

    介绍

    剑指 Offer 18. 删除链表的节点

    题目

    给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。

    返回删除后的链表的头节点。

    示例 1:
    输入: head = [4,5,1,9], val = 5
    输出: [4,1,9]
    解释: 给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9.
    
    示例 2:
    输入: head = [4,5,1,9], val = 1
    输出: [4,5,9]
    解释: 给定你链表中值为 1 的第三个节点,那么在调用了你的函数之后,该链表应变为 4 -> 5 -> 9.
    
    说明:
    题目保证链表中节点的值互不相同
    若使用 C 或 C++ 语言,你不需要 free 或 delete 被删除的节点
    

    思路

    • 特例处理: 当应删除头节点 head 时,直接返回 head.next 即可。
    • 初始化: pre = head , cur = head.next 。
    • 定位节点: 当 cur 为空 或 cur 节点值等于 val 时跳出。
      • 保存当前节点索引,即 pre = cur 。
      • 遍历下一节点,即 cur = cur.next 。
    • 删除节点: 若 cur 指向某节点,则执行 pre.next = cur.next 。(若 cur 指向 nullnull ,代表链表中不包含值为 val 的节点。
    • 返回值: 返回链表头部节点 head 即可。

    代码

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode deleteNode(ListNode head, int val) {
            if(head.val == val){
                return head.next;
            }
            ListNode pre = head, cur = head.next;
            while(cur != null && cur.val != val){
                pre = cur;
                cur = cur.next;
            }
            if(cur != null){
                pre.next = cur.next;
            }
            return head;
        }
    }
    

    感谢

    Leetcode

    以及勤劳的自己,个人博客GitHub

    微信公众号

  • 相关阅读:
    poj3669 广搜
    检索所有课程都选修的的学生的学号与姓名
    UVA10160 Servicing Stations
    uva11205 The broken pedometer 子集生成
    poj1101 the game 广搜
    poj3009 Curling 2.0 深搜
    poj 1564 Sum It Up 搜索
    HDU 2268 How To Use The Car (数学题)
    codeforces 467C George and Job(简单dp,看了题解抄一遍)
    HDU 2267 How Many People Can Survive(广搜,简单)
  • 原文地址:https://www.cnblogs.com/guizimo/p/13644209.html
Copyright © 2011-2022 走看看