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


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

解题思路

单链表,一看就用快慢指针。没啥说的

代码

/**
 * 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) {
        //base case
        if(head.val==val){
            return head.next;
        }
        ListNode slow=head;
        ListNode fast=head.next;
        while(slow!=null&&fast.val!=val){
            slow=slow.next;
            fast=fast.next;
        }
        //fast到达了目标值
        slow.next=fast.next;
        return head;
    }
}

文章作者: fFee-ops
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 fFee-ops !
评论
  目录