0
点赞
收藏
分享

微信扫一扫

Leetcode剑指Offer刷题 - 第十天

日月同辉9908 2022-02-03 阅读 53

剑指 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) {
        //判空
        if (head == null) return head;
        //设定cur代表当前节点和pre代表上一个节点
        ListNode cur = head;
        ListNode pre = null;
        //判断首节点是否为要删除节点,如果是,直接返回下一个节点
        if (cur.val == val) return cur.next;
        //不是要删除节点就向后走
        while (cur.val != val) {
            pre = cur;
            cur = cur.next;
        }
        //找到了要删除节点
        pre.next = pre.next.next;

        return 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 == null) return head;
        if (head.val == val) return head.next;
        ListNode cur = head;
        while (cur.next != null && cur.next.val != val) {
            cur = cur.next;
        }
        if (cur.next != null) {
            cur.next = cur.next.next;
        }

        return head;
    }
}

剑指 Offer 22. 链表中倒数第k个节点

解法:快慢指针

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode getKthFromEnd(ListNode head, int k) {
        if (head == null) return head;
        ListNode slow = head;
        ListNode fast = head;
        //fast先走k步
        while (k > 0 && fast != null) {
            fast = fast.next;
            k--;
        }
        //slow和fast一起走
        while (fast != null) {
            slow = slow.next;
            fast = fast.next;
        }

        return slow;
    }
}
举报

相关推荐

每日刷题:第十天 移除链表元素

python(第十天)

【JavaSE 第十天】

web第十天

HCIP第十天

第十天学习

LeetCode刷题(剑指offer)

0 条评论