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

题目:

思路:

【1】本身在于边界的判断,但是对于一开始添加一个节点这个做法虽然能过,但是不太严谨,应该采取后面那种,因为如果链表的目标值就是0的话,那么第一种就坐蜡了。

代码展示:

//时间0 ms击败100%
//内存41 MB击败54.94%
/**
 * 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) {
        ListNode res = new ListNode(0);
        res.next = head;
        ListNode temp = res;
        while (temp != null && temp.next != null){
            if (temp.next.val == val ){
                temp.next = temp.next.next;
            }
            temp = temp.next;
        }
        return res.next;
    }
}

//时间0 ms击败100%
//内存41.2 MB击败26.46%
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;
    }
}

 

posted @ 2023-02-14 00:54  忧愁的chafry  阅读(9)  评论(0编辑  收藏  举报