剑指 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 null;
        //如果头结点为 要删除的节点
        if(head.val == val) return head.next;
        //其他情况,先保存头结点信息,便于删除后直接返回
        ListNode pre = head;
        ListNode cur = head.next;

        while(cur.val != val && cur != null){
            pre = cur;
            cur = cur.next;
        }
        //找到该节点,删除
        if(cur != null){
            pre.next = cur.next;
        }
        return head;
    }
}

 

posted @ 2020-12-14 13:26  peanut_zh  阅读(49)  评论(0编辑  收藏  举报