剑指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) {
    
    
        //如果要删除的是头结点,则直接返回
        if (head.val == val) return head.next;
        //双指针
        ListNode pre = head, cur = head.next;

        while (cur != null && cur.val != val) {
    
    
            pre = pre.next;
            cur = cur.next;
        }
        if (cur != null) {
    
    
            pre.next = cur.next;
        }
        return head;
    }
}

猜你喜欢

转载自blog.csdn.net/cys975900334/article/details/114933762