移除链表元素 (Remove Linked List Elements)

 

思路:

// @Title: 移除链表元素 (Remove Linked List Elements)
// @Author: qisiii
// @Date: 2024-09-12 00:33:16
// @Runtime: 1 ms
// @Memory: 44.3 MB
// @comment: 
// @flag: 
/**
 * Definition for singly-linked list.
 * public class ListNode {
 * int val;
 * ListNode next;
 * ListNode() {}
 * ListNode(int val) { this.val = val; }
 * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode removeElements(ListNode head, int val) {
        ListNode cur = head, old = new ListNode(-1, head), result = old;
        while (cur != null) {
            int value = cur.val;
            if (value == val) {
                old.next = cur.next;
            }else{
                old = cur;
            }
            cur = cur.next;
        }
        return result.next;
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18